LEFT JOIN中的COUNT返回重复值

时间:2016-02-11 04:40:35

标签: php mysql join left-join

我有以下表格(示例):

用户

id | user | photo   | joined | country
1  | Igor | abc.jpg | 2015   | Brazil
2  | John | cga.png | 2014   | USA
3  | Lucas| hes.jpg | 2016   | Japan

帖子(请参阅author = Igorft = 2两行,author = Igorft = 3一行,Igor有三个帖子):

id | author | content | date | ft (2 = photos and 3 = videos)
1  | Igor   | hi      | 2016 | 2
2  | Igor   | hello   | 2016 | 3
3  | John   | hehehe  | 2016 | 2
4  | Igor   | huhuhuh | 2016 | 2
5  | Lucas  | lol     | 2016 | 3

友谊(当status = 2表示他们是朋友时):

id | friend1 | friend2 | status
1  | Igor    | Lucas   | 2
2  | Lucas   | John    | 2
3  | John    | Igor    | 2

我希望根据当前记录的COUNTft = 2COUNT朋友(status = 2)进行SELECT photo, joined, country, sum(CASE WHEN ft = 2 THEN 1 ELSE 0 END) AS numPhotos, sum(CASE WHEN ft = 3 THEN 1 ELSE 0 END) AS numVideos FROM users LEFT JOIN posts ON users.user = posts.author WHERE users.user = 'Igor' GROUP BY users.user LIMIT 1 帖子用户(Igor,在这种情况下)。

所以,我这样做(假设当前用户登录的是 Igor ):

foreach

当我查看numPhotos = 2时,数据是正确的: numVideos = 1SELECT photo, joined, country, sum(CASE WHEN ft = 2 THEN 1 ELSE 0 END) AS numPhotos, sum(CASE WHEN ft = 3 THEN 1 ELSE 0 END) AS numVideos, count(friendship.status) AS numFriends FROM users LEFT JOIN posts ON users.user = posts.author LEFT JOIN friendship ON (users.user = friend1 OR users.user = friend2) AND friendship.status = 2 WHERE users.user = 'Igor' GROUP BY users.user LIMIT 1

但是,我想选择朋友的数量,所以,我这样做:

numPhotos = 4

但是,输出是: numVideos = 2numFriends = 6numFriends

换句话说,他正在重复所有结果,但在count(friendship.status)中,他取了Igor(3)的总帖子并重复了这个值。如果我将sum(friendship.status)更改为numPhotos = 4,则输出为: numVideos = 2numFriends = 18numFriendscount(distinct friendship.status)的三倍)。

我也尝试使用numPhotos = 4,结果如下: numVideos = 2numFriends = 1numFriends(重复这些值,并为count(distinct friendship.status)返回错误的值1,知道他有两个朋友,应该是2。

那么,我怎么能这样做? (我使用的是MySQL)

修改

我将count(distinct friendship.id)更改为numPhotos,并且可以选择朋友的数量。但其余值(numVideosON (users.user = friend1 OR users.user = friend2))仍然重复。

我发现问题出在ON (users.user = friend1),因为如果我只留下ON (users.user = friend2)ON 'Igor' IN (friend1, friend2) but the result is the same (,则输出不会重复。我也试过and numPhotos {{1}} numVideos`继续重复)。

2 个答案:

答案 0 :(得分:3)

我认为左连接可能正在加入一对多关系,导致计数膨胀。 由于您只检索1个用户的计数,我建议使用子查询来检索友谊计数(为了检索多个用户的计数,派生表可能比子查询更快):

SELECT 
    sum(ft = 2) AS numPhotos, 
    sum(ft = 3) AS numVideos,
    (select count(*) from friendships f
    where (friend1 = users.user 
    or friend2 = users.user)
    and status = 2) as friendship_count
FROM users
LEFT JOIN posts
ON users.user = posts.author
WHERE users.user = 'Igor'

请注意,我删除了group by,因为users.user已经在where子句中,这意味着只有一个组。

答案 1 :(得分:2)

而不是count(distinct friendship.status),请尝试使用count(distinct friendship.id)。这应该会给你一些独特的朋友。计算不同的状态并不起作用,因为根据定义,所有状态都是2,因此只有一个不同的值。