SQL从两个表中获取结果

时间:2017-11-04 20:18:47

标签: mysql sql

我有两张桌子:

 table : game

 id     mdate             stadium                 team1     team2
1001    8 June 2012     National Stadium, Warsaw    POL     GRE
1002    8 June 2012     Stadion Miejski (Wroclaw)   RUS     CZE
1003    12 June 2012    Stadion Miejski (Wroclaw)   GRE     CZE
1004    12 June 2012    National Stadium, Warsaw    POL     RUS
....

 table goal 

 matchid    teamid  player              gtime
 1001        POL    Robert Lewandowski      17
 1001        GRE    Dimitris Salpingidis    51
 1002        RUS    Alan Dzagoev            15
 1002        RUS    Roman Pavlyuchenko      82
 ...

注意:以上两个表都很长,因此结果表可能会显示两个表中未显示的行。

需要找到每支球队得分各项的比赛

 mdate         team1    score1  team2   score2
 1 July 2012    ESP        4    ITA     0
 10 June 2012   ESP        1    ITA     1
 10 June 2012   IRL        1    CRO     3

我的解决方案:

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

我不确定我的解决方案是否正确,但其结构又长又丑。

任何人都可以建议更好的解决方案吗?

可以用CASE WHEN解决它吗?

2 个答案:

答案 0 :(得分:1)

最简单的方法可能是相关的子查询:

select m.mdate, m.team1,
   (select count(*)
    from goal g
    where g.teamid = m.team1 and g.matchid = m.id
   ) as team1_goals,
   m.team2,
   (select count(*)
    from goal g
    where g.teamid = m.team2 and g.matchid = m.id
   ) as team2_goals
from game m
ORDER BY m.mdate, m.team1, m.team2;

这种方法的一个优点是它可以利用goals(matchid, teamid)上的索引。

答案 1 :(得分:0)

好的......找到了网站,让它开始工作

SELECT g.mdate, g.team1, CASE WHEN g2.score1 IS NULL THEN 0 ELSE g2.score1 END, g.team2, CASE WHEN g3.score2 IS NULL THEN 0 ELSE g3.score2 END 
FROM game g LEFT OUTER JOIN 
    (SELECT matchid, teamid, COUNT(*) score1 from goal group by matchid, teamid) g2 ON g.team1 = g2.teamid AND g.id = g2.matchid
LEFT OUTER JOIN  
    (SELECT matchid, teamid, COUNT(*) score2 from goal group by matchid, teamid) g3 ON g.team2 = g3.teamid AND g.id = g3.matchid 
ORDER BY g.mdate, g.team1, g.team2
哇... mariadb对表名等情况非常恶毒。

CASE用于处理返回null的场景