我有如下表(例如):COUNT在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 = Igor
和ft = 2
和一行author = Igor
和ft = 3
和伊戈爾有三個職位):
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
而且我想根據當前登錄用戶做帖子與ft = 2
和朋友COUNT
(status = 2
)的COUNT
(伊戈爾,在這種情況下)。
所以,我(假設登錄的當前用戶伊戈爾):
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
當我查了foreach
,該數據是正確的: numPhotos = 2
和numVideos = 1
。
但是,我想選擇過的朋友的數量,所以,我做的:
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, 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 = 2
和numFriends = 6
。
換句話說,他正在複製所有結果,但在numFriends
他正在佔用Igor(3)的帖子總數並重復該值。如果我將count(friendship.status)
更改爲sum(friendship.status)
,則輸出爲: numPhotos = 4
,numVideos = 2
和numFriends = 18
(將numFriends
三元化)。
我count(distinct friendship.status)
嘗試過,結果是: numPhotos = 4
,numVideos = 2
和numFriends = 1
(複製該值再次以及返回numFriends
錯誤值1,應該是2知道他有兩個朋友)。
那麼,我該如何做到這一點? (我使用MySQL)
編輯:
我改變了count(distinct friendship.status)
到count(distinct friendship.id)
和它的工作選擇的朋友的數量。但其餘值(numPhotos
和numVideos
)繼續重複。
我發現問題出在ON (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 (
numPhotos and
numVideos`繼續複製)。
完美!謝謝! – Igor