我在找到这个小问题的解决方案时遇到了一些麻烦。我想得到团队的数量,我也需要零数。如果我不提及特定的团队,这是有效的。但是当查询变得复杂时无法工作。
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
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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