MySQL为体育团队加入两个查询

时间:2014-02-15 03:16:51

标签: mysql sql

我正在尝试显示一个团队列表,其中包含他们已经得分的目标数量(并按最大到最小的顺序排列)但是我们在加入所有查询时遇到了麻烦

表1:团队

teamid teamname
  1      team1
  2      team2
  3      team3

表2:结果

 id gameid teamid gf
  1    1     1    5
  2    2     1    3
  3    1     2    0
  4    2     2    2
  5    3     3    0

我想要实现的目标

  1. Team1 8
  2. Team2 2
  3. Team3 0

获取所有团队的列表

SELECT team.teamid, team.teamname
 FROM teams team

获取1支队伍的目标总和

SELECT COALESCE( SUM( gf ) , 0 ) goalsfor
FROM results
WHERE teamid = 1

加入查询

SELECT team.teamid,
       team.teamname,
       COALESCE(res.gf, 0) goalsfor
FROM teams team
LEFT JOIN
  (SELECT COALESCE(SUM(res.gf), 0) goalsfor
   FROM results res
   GROUP BY teamid) res ON team.teamid = res.teamid
ORDER BY goalsfor DESC

一直坚持加入查询

2 个答案:

答案 0 :(得分:1)

我的解决方案是:

SELECT t.id,
    t.name,
    SUM(r.gf) goalsfor
FROM team t
LEFT JOIN
    results r ON t.id = r.teamId
GROUP BY t.id
ORDER BY goalsfor DESC

我的假表的结果:

id name     goalsfor
1  Apple    8
2  Banana   2
3  Carrot   0

如果您的列的默认值为0且不能为null,我认为您不需要COALESCE

答案 1 :(得分:1)

SELECT teams.teamname, res.goals FROM teams JOIN (
    SELECT COALESCE(SUM(results.gf),0) AS goals, results.teamid AS teamid FROM results
    group by results.teamid) res
ON teams.teamid=res.teamid ORDER BY goals DESC;