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

时间:2018-07-11 18:08:33

标签: mysql sql pdo

我有一个名为league_ranking的表,其中包含round中所有可用teams的特定competition的排名。 现在发生的情况是,某些roundsleague_ranking表中没有任何值,因此在这种情况下,我想防止在competitions的列表中出现{{1} },其中competition中几乎没有round

这是我的查询

league_ranking

数据示例和表结构

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

competition_rounds

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

competition_seasons

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

竞争

|id | competition_id
 577      28
 578      28

您可以看到|id | name 28 Premier 6在round中没有值,问题是我的查询甚至返回了竞争league_ranking,我该如何防止返回此值Premier几乎有competition没有价值?

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用LEFT JOIN而不是INNER JOIN,需要基于Outer JOIN表的competition_rounds

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