在SQLZoo中加入SQL#13的解决方案

时间:2014-09-14 19:45:54

标签: mysql sql join

链接为http://sqlzoo.net/wiki/The_JOIN_operation。问题13。 现在我可以列出所有匹配项,只要代码中至少有一个目标:

SELECT mdate, 
       team1, 
       SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) AS score1, 
       team2, 
       SUM(CASE WHEN teamid = team2 THEN 1 ELSE 0 END) AS score2 FROM
    game JOIN goal ON (id = matchid)
    GROUP BY id
    ORDER BY mdate, matchid, team1, team2

然而,有些比赛的得分为0:0。我的代码无法显示这些游戏,也无法找到其他可用的解决方案。真的希望有人可以帮我解决这个问题。

3 个答案:

答案 0 :(得分:3)

托盘LEFT JOIN代替JOIN。因为即使没有目标,你也需要展示所有游戏。

答案 1 :(得分:3)

SELECT mdate, 
       team1, 
       SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) AS score1, 
       team2, 
       SUM(CASE WHEN teamid = team2 THEN 1 ELSE 0 END) AS score2 FROM
    game LEFT JOIN goal ON (id = matchid)
    GROUP BY mdate,team1,team2
    ORDER BY mdate, matchid, team1, team2

你想在SELECT中没有聚合函数的GROUP BY列,并使用LEFT JOIN。

答案 2 :(得分:1)

SELECT G.mDate
      ,G.Team1
      ,ISNULL( (SELECT COUNT(*) FROM goal WHERE teamid = G.Team1), 0) AS Team1_Goals 
      ,G.Team2
      ,ISNULL( (SELECT COUNT(*) FROM goal WHERE teamid = G.Team2), 0) AS Team2_Goals      
FROM Game G 
WHERE EXISTS (SELECT 1
              FROM goal 
              WHERE matchid = G.matchid)