2016-02-11 93 views
1

我有如下表(例如):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 = Igorft = 2和一行author = Igorft = 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和朋友COUNTstatus = 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 = 2numVideos = 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 = 4numVideos = 2numFriends = 6

換句話說,他正在複製所有結果,但在numFriends他正在佔用Igor(3)的帖子總數並重復該值。如果我將count(friendship.status)更改爲sum(friendship.status),則輸出爲: numPhotos = 4numVideos = 2numFriends = 18(將numFriends三元化)。

count(distinct friendship.status)嘗試過,結果是: numPhotos = 4numVideos = 2numFriends = 1(複製該值再次以及返回numFriends錯誤值1,應該是2知道他有兩個朋友)。

那麼,我該如何做到這一點? (我使用MySQL)

編輯

我改變了count(distinct friendship.status)count(distinct friendship.id)和它的工作選擇的朋友的數量。但其餘值(numPhotosnumVideos)繼續重複。

我發現問題出在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`繼續複製)。

回答

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個組。

+0

完美!謝謝! – Igor

2

而不是count(distinct friendship.status),請嘗試使用count(distinct friendship.id)。這應該給你一些獨特的朋友。計數不同的狀態不起作用,因爲所有狀態的定義都是2,所以只有一個不同的值。

+0

它的工作原理!但其餘的值('numPhotos'和'numVideos')繼續重複。 – Igor