2012-11-24 124 views
3

重複的結果我有2 MySQL表一個名爲「用戶」和另一個名爲「連接」MYSQL連接即使DISTINCT

表的用戶對用戶的信息,並有3行:

mikha 
guy 
maricela 

表連接有用戶喜歡的Twitter之間的連接(mikha以下maricela和maricela以下mikha例如)

連接具有以下行:

username1  | username2 
-------------------------- 
guy   | maricela 
mikha   | guy 
mikha   | maricela 

我想獲得有關'mikha'的信息,包括他追蹤的人數和追隨他的人數。

我用下面的查詢:

SELECT *, COUNT(DISTINCT connections.username1) AS count_following, 
    COUNT(DISTINCT connections.username2) AS count_followers 
FROM users LEFT JOIN connections on connections.username1 = 'mikha' OR 
    connections.username2 = 'mikha' WHERE users.username = 'mikha' 

預計:

count_following = 2 (as mikha is following guy and maricela) 
count_followers = 0 (no one following mikha yet) 

實際:

count_following = 2 
count_followers = 1 

感謝 問候 邁克爾

回答

1

您可以運行兩個不同的查詢(fiddle here):

select 
    (select count(*) from connections 
    where username1 = 'mikha') following, 
    (select count(*) from connections 
    where username2 = 'mikha') followers 

或使用此(fiddle here):

select 
    sum(username1 = 'mikha') following, 
    sum(username2 = 'mikha') followers 
from connections 

我覺得第二個應該會更快。一旦你得到這個只是加入你的用戶表,以防你需要從該表中額外的信息(給你的例子,你不)。