外连接 - 不工作,不显示空行

时间:2014-02-15 04:09:48

标签: mysql sql

我有一个查询可以完成一些事情。首先,它应该让所有团队的divisionid为1.然后它应该获得在结果列中注册的胜利数量。

它实现了这一点,但是如果团队在结果表中没有注册数据,则不会显示TeamName 0(wins)。关于为什么会发生这种情况的任何想法?

表1:活跃团队

 aid teamid divisionid
  1    1        1
  2    2        1
  3    3        1
  4    4        2

表2:团队

  teamid teamname 
    1     Argos
    2     Leafs 
    3     Blue Jays
    4     Ducks

表3:结果   摆脱teamid的结果    1 1'w'    2 2'l'

最终结果目标

 divid teamname  wins
   1     Argos    1
   1     Leafs    0
   1     Bluejays 0

当前查询

SELECT activeteams.divisionid, teams.teamname, res.wins
FROM activeteams
JOIN teams ON activeteams.teamid = teams.teamid
  OUTER JOIN (
    SELECT 
      COALESCE(SUM(CASE WHEN result =  'w' THEN 1 ELSE 0 END ), 0) AS wins, 
      results.teamid AS teamid
  FROM results
  GROUP BY results.teamid
  )res ON teams.teamid = res.teamid
WHERE activeteams.divisionid = 1

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

SELECT activeteams.divisionid, teams.teamname, res.wins
FROM activeteams
INNER JOIN teams ON activeteams.teamid = teams.teamid
LEFT JOIN (
    SELECT 
        COALESCE(SUM(CASE WHEN result =  'w' THEN 1 ELSE 0 END ), 0) AS wins, 
        teamid
    FROM results
    GROUP BY teamid
  ) res ON teams.teamid = res.teamid
WHERE activeteams.divisionid = 1