SQLzoo JOIN教程#13

时间:2013-03-15 18:40:19

标签: mysql sql join

我一直在研究SQLzoo问题,但在JOIN教程问题#13中遇到最后一个问题 - 列出每个匹配的每个团队所显示的目标。

链接:http://sqlzoo.net/wiki/The_JOIN_operation

在他们提供的示例代码中,它使用了一个案例。我这样修改了它:

SELECT game.mdate, game.team1,
  CASE WHEN goal.teamid=game.team1 THEN 1 ELSE 0 END score1, game.team2,
  CASE WHEN goal.teamid=game.team2 THEN 1 ELSE 0 END score2
  FROM game, goal WHERE game.id=goal.matchid
GROUP BY game.mdate, goal.matchid, game.team1, game.team2

他们建议在score1 / score2上使用SUM函数将提供答案。我对如何在SQL中创建的这两列使用SUM函数感到困惑。

任何人都可以提供一个提示,说明如何以更好的方式编写或提及如何以更好的方式编写此SQL查询?

4 个答案:

答案 0 :(得分:12)

这对我有用,可以修正左连接。

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

答案 1 :(得分:3)

嗯,你需要SUM这些列(SUM是一个聚合函数,这就是你有GROUP BY的原因。至于以更好的方式编写查询,您需要丢失旧的隐式JOIN样式并使用ANSI显式样式:

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

答案 2 :(得分:3)

你的SQL非常好,你只需要一个SUM聚合函数的好例子 这是我的解决方案:

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

注意:我的原始帖子的值不正确,需要使用LEFT JOIN代替INNER JOIN。当两个团队都有0分时,左连接会处理这种情况,内连接不会接收这些情况。

答案 3 :(得分:0)

我认为SQLzoo问题已更新,以上答案似乎无法完全解决问题#13。请注意,现在需要排序ORDER BY子句。

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 (
                goal.matchid = game.id                 
            )          
    GROUP BY
        mdate,
        team1,
        team2          
    ORDER BY
        mdate,
        matchid,
        team1,
        team2     ;