如果几乎一个内部连接条件没有值,如何返回null?

ulmd4ohb  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(316)

我有一张table叫 league_ranking 其中包含特定 round 对于所有的 teams 可在 competition . 现在碰巧 rounds 没有任何价值 league_ranking 表,所以在这种情况下,我想在 competitions 出现 competition 几乎有一个 round 没有价值 league_ranking .
我的问题是:

SELECT c.name AS competition_name,
  c.id AS competition_id
  FROM competition c
  INNER JOIN competition_seasons s ON s.competition_id = c.id
  INNER JOIN competition_rounds r ON r.season_id = s.id
  INNER 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

数据示例和表结构
联赛排名

|position | team_id | round_id | 
     1        120        5
     2        124        5

比赛回合

| id | season_id | name 
   5       577      First Round
   6       578      Preliminary Round

比赛季

|id | competition_id
 577      28
 578      28

竞争

|id | name 
  28  Premier

你可以看到 round 6.里面没有价值观 league_ranking ,问题是我的查询甚至返回竞争对手 Premier ,我怎样才能防止退货呢 competition 几乎有一个 round 没有价值?
谢谢。

cbwuti44

cbwuti441#

你可以试着用 LEFT JOIN 而不是 INNER JOIN ,你需要 Outer JOIN 基于 competition_rounds table。

SELECT c.name AS competition_name,
c.id AS competition_id
FROM  competition_rounds r 
LEFT JOIN competition_seasons s ON r.season_id = s.id
LEFT JOIN competition c ON s.competition_id = c.id
LEFT 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

sqlfiddle公司

相关问题