我正在尝试显示球队列表及其进球数(并按从大到小排序),但无法将所有查询连接在一起
表 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
整天都在加入查询
最佳答案
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;
关于MySQL 连接运动队的两个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21792937/