SQL查询不起作用。计数也应该返回零。但即使在外连接之后也无法工作

时间:2017-07-31 13:18:29

标签: mysql sql-server

我在找到这个小问题的解决方案时遇到了一些麻烦。我想得到团队的数量,我也需要零数。如果我不提及特定的团队,这是有效的。但是当查询变得复杂时无法工作。

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

3 个答案:

答案 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