求和返回多行的SELECT的结果

时间:2016-11-15 18:26:31

标签: mysql sql select sum

我试图将返回多行的select的结果相加: 我有四个表(用户,团队,飞行员,结果):

user (id_user)
team (id_user, id_team)
pilot (id_pilot, id_team)
result (id_pilot, id_gp, points)

当我这样做时:

SELECT p.id_team, SUM( r.points ) AS TOTAL
FROM pilot p
LEFT JOIN result r ON p.id_pilot = r.id_pilot
WHERE r.id_grand_prix =  '1'
GROUP BY p.id_team

我得到:

id_team TOTAL
-------------
1 10
2 15
3 5
4 6
5 7

我想要的是,如果id_user有id_team 1和2有25分。

我试试:

UPDATE user AS u 
JOIN has_team ON u.id_user = has_team.id_user 
JOIN (
    SELECT p.id_team, SUM( r.position ) AS TOTAL
    FROM pilot p
    LEFT JOIN result r ON p.id_pilot = r.id_pilot
    WHERE r.id_grand_prix =  '1'
    GROUP BY p.id_team
    ) AS grp 
  ON grp.id_team = has_team.id_team
SET u.points = grp.TOTAL + u.points

但我只有一支球队的分数。

事先非常多可以帮助我。

1 个答案:

答案 0 :(得分:0)

您是否希望获得每个用户而非每个团队的积分总和?

如果是这样,您的查询可能是这样的:

SELECT u.id_user, SUM( r.points ) AS TOTAL
FROM pilot p
LEFT JOIN result r ON p.id_pilot = r.id_pilot
INNER JOIN team t ON p.id_team = t.id_team
INNER JOIN user u ON t.id_user = u.id_user
WHERE r.id_grand_prix =  '1'
GROUP BY u.id_user

如果没有,你能澄清一下你需要展示什么吗?