2011-02-27 58 views
11

比方說,我有以下表結構:是否有可能在同一個查詢來算兩列

t1 
------------- 
id // row id 
userID_follower // this user is a follows another member 
userID_following // other member that this user 

是否有可能運行一個查詢到以下兩者結合:

  1. 有多少用戶這個人以下從T1 WHERE userID_follower =

    SELECT COUNT(ID) 「$身份識別碼。」 。 「

  2. 多少用戶遵循從T1這個人

    SELECT COUNT(ID),其中userID_following =」 $身份識別碼。」

感謝。

回答

44

在MySQL中,你可以使用SUM()功能上的條件,因爲一個錯誤的條件將等於0,和一個真正的人會等於1

SELECT SUM(userID_follower = $myID) AS followerCount, 
    SUM(userID_following = $myID) AS followingCount 
FROM t1 
WHERE userID_follower = $myID 
    OR userID_following = $myID 
+1

我的天啊。這給了子集數量很多的優點,而不需要通過where子句來篩選整個選擇。非常感謝! – C4u 2015-12-01 15:03:24

+0

你爲什麼需要where子句? – 2017-09-07 19:11:58

+0

@IstiaqueAhmed列應該被索引。不需要進行全表掃描。 – 2017-09-08 08:05:56

1

我認爲這樣的事情應該可以工作:

select ownerID, count(distinct userID_follow), count(distinct userID_following) from t1 group by ownerID 
+0

哦,你是對的,但我如何得到的計數值?我應該如AS cont1和AS cnt2? – santa 2011-02-27 13:34:14

+0

是的,'count(distinct userID_follow)as cnt1' should be working。 – SiggyF 2011-02-27 17:30:46

2

我建議返回兩列一個計數每一行,而不是兩列:

SELECT 'follower', COUNT(*) AS count FROM t1 WHERE userID_follower = ? 
UNION ALL 
SELECT 'following', COUNT(*) FROM t1 WHERE userID_following = ? 

這可能看起來是簡併的解決方案,但其原因是,如果userID_follower和userID_following是指數編輯,這可以利用指標。如果您嘗試按照其他答案中所示的方式將結果顯示在兩列中,則無法使用索引並必須執行表掃描。

其他提示,相切的問題:

  • 沒有什麼優勢,在這種情況下使用COUNT(ID)。
  • 您應該使用SQL查詢參數,而不是將$ myID插入到查詢中。
+0

'不能使用索引並且必須執行表掃描',這是不正確的。請參閱http://dev.mysql.com/doc/refman/5.0/en/index-merge-optimization。html – 2011-03-03 22:08:03

+0

@Scrum:Aha,你說得對,如果我用更多的隨機數據測試幾千行,MySQL確實會使用索引並執行聯合合併。我測試過的行數太少,或者沒有足夠的隨機分佈。 – 2011-03-03 22:54:17

8

更霍伊爾(ISO)的解決辦法是使用CASE表達式:

Select Sum(Case When userID_follower = $myID Then 1 Else 0 End) As followerCount 
    , Sum(Case When userID_following = $myID Then 1 Else 0 End) As followingCount 
From t1 
Where userID_follower = $myID 
    Or userID_following = $myID 
+0

沒有事件需要CASE,因爲我的列是int。謝謝! – Dan 2013-09-13 20:57:38

相關問題