2017-07-31 23 views
1

我在尋找這個小問題的解決方案時遇到了一些麻煩。我想要得到球隊的人數,同時我也需要零計數。如果我沒有提到具體的團隊,這是行得通的。但在查詢變得複雜時失敗。SQL查詢不起作用。計數也應歸零。但即使在外部連接後也不能工作

SELECT teams.name, COUNT(checkins.team_id) AS "count of checkins" 
FROM checkins 
    RIGHT JOIN teams ON checkins.team_id = teams.id 
GROUP BY checkins.team_id 

這未能奏效時,它改變這樣

SELECT teams.name, COUNT(checkins.team_id) AS "count of checkins" 
FROM checkins 
    RIGHT JOIN teams ON checkins.team_id = teams.id 
    WHERE checkins.team_id IN (1,3,2) 
GROUP BY checkins.team_id 
+1

用你最右邊的表WHERE條件,因爲它是在TEAM_ID,你會好起來: 'WHERE teams.id IN(1,3,2)'。如果你是想從所有球隊'teams'表然後切換是一個'團隊LEFT OUTER JOIN checkins'並把限制ON子句'ON teams.id = checkins.team_id並在checkins.team_id(1,3中, 2)' – JNevill

+0

標籤衝突,請更正。 – KtX2SkD

+0

@ KtX2SkD謝謝你。 –

回答

0

希望這個作品如預期

SELECT teams.name, COUNT(checkins.team_id) AS "count of checkins" 
FROM checkins 
    RIGHT JOIN teams ON checkins.team_id = teams.id 
    WHERE checkins.team_id IN ('1','3','2') 
GROUP BY checkins.team_id 
2

你可以試試這個:

SELECT teams.name, COUNT(checkins.team_id) AS "count of checkins" 
FROM checkins 
    RIGHT JOIN teams ON checkins.team_id = teams.id 
    WHERE (checkins.team_id IN (1,3,2) OR checkins.team_id IS NULL) 
GROUP BY checkins.team_id 
2

你可以移動WHERE IN ...條件設定爲ON條款:

SELECT 
    teams.name, 
    COUNT(checkins.team_id) AS "count of checkins" 
FROM checkins 
RIGHT JOIN teams 
    ON checkins.team_id = teams.id AND checkins.team_id IN (1,3,2) 
GROUP BY checkins.team_id 

您的最新變化正在改變計數的原因是聚集發生之前的WHERE子句過濾掉的記錄。通過將所有內容移動到ON子句中,連接將保留加入右側的所有原始記錄進入聚合。

但大多數的時候,我們會用寫這個查詢LEFT JOIN,而不是正確的:

SELECT 
    teams.name, 
    COUNT(checkins.team_id) AS "count of checkins" 
FROM teams 
LEFT JOIN checkins 
    ON teams.id = checkins.team_id AND checkins.team_id IN (1,3,2) 
GROUP BY checkins.team_id 
相關問題