我不是MySQL专家,需要一些查询帮助。
table(t_teams)
团队|小组
Germany | A
Russia | B
Danmark | A
Japan | C
.....
table(t_matches)
id | fk_team1 | fk_team2 | points_team1 | points_team2
1 | Germany | Russia | 3 | 0
2 | Danmark | Japan | 3 | 0
3 | Germany | Japan | 3 | 0
4 | Russia | Danmark | 1 | 1
外键是: fk_team1 fk_team2
现在,我想通过mysql查询对每个团队的t_matches中的所有点进行求和。 最终结果应该是
**team | points**
Germany | 6
Russia | 1
Danmark | 1
Japan | 0
我尝试过类似的东西,但它不起作用: - (
SELECT
t1.team,
SUM(t2.points_team1) + SUM(t2.points_team2) AS points
FROM t_teams t1, t_matches t2
WHERE (t1.team = t2.fk_team1) OR (t1.team = t2.fk_team2)
当有人可以帮我解决这个简单的查询时,会很棒。
答案 0 :(得分:2)
您需要取消数据,然后汇总结果:
select team, sum(points)
from ((select fk_team1 as team, points_team1 as points from t_teams t
) union all
(select fk_team2 as team, points_team2 as points from t_teams t
)
) t
group by team;