即使使用DISTINCT,MYSQL也会加入重复的结果

时间:2012-11-24 00:33:57

标签: php mysql database join duplicates

我有2个mysql表,一个名为'users',另一个名为'connections'

表用户有关于用户的信息,有3行:

mikha
guy
maricela

表连接之间有用户之间的联系,例如twitter(mikha跟随maricela和maricela跟随mikha)

Connections具有以下行:

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 个答案:

答案 0 :(得分: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

我认为第二个应该更快。一旦你得到它只是加入你的用户表,以防你需要从该表中的额外信息(给出你的例子,你没有)。