无法排除未加入的记录

时间:2019-04-08 08:28:16

标签: mysql sql

我只需要返回具有排名的比赛,该排名位于表league_ranking内,每个比赛都与round_id列相关。

基本上,查询应该返回特定国家/地区的所有比赛,但条件是该国家/地区的所有比赛都必须具有排名,所以我这样做了:

SELECT c.name AS competition_name,
  c.id AS competition_id
  FROM competition c
  JOIN competition_seasons s ON s.competition_id = c.id
  JOIN competition_rounds r ON r.season_id = s.id
  LEFT JOIN league_ranking l ON l.round_id = r.id
  WHERE c.country_id = :country_id AND l.round_id IS NULL
  GROUP BY c.id
  ORDER BY c.name ASC

此查询还返回没有排名的竞争,例如:

竞争

id | country_id | name
202     12         Cup

competition_seasons

id  | competition_id | name
955       202           2018/2019

competition_rounds

id    | season_id |
 2122    955

联赛排名

该回合没有记录

上面的查询还将返回竞争202,我做错了什么?

2 个答案:

答案 0 :(得分:1)

您当前的查询专门用于仅返回排名为 no 的比赛,因为它使用LEFT JOINleague_ranking,然后检查{{1} },只有在比赛没有联赛排名时(即没有与l.round_id IS NULL匹配的行),这才是正确的。如果您只想拥有联赛排名的<​​em> 比赛,请将l.round_id = r.id更改为LEFT JOIN,然后删除JOIN条件。请注意,您不需要l.round_id IS NULL子句,而我已将其删除。

GROUP BY

Demo on dbfiddle

答案 1 :(得分:0)

请尝试此查询

SELECT c.name AS competition_name, c.id AS competition_id FROM competition c JOIN competition_seasons s ON s.competition_id = c.id JOIN competition_rounds r ON r.season_id = s.id JOIN league_ranking l ON l.round_id = r.id WHERE c.country_id = :country_id GROUP BY c.id ORDER BY c.name ASC