使用另一个表中的SUM更新表

时间:2012-04-10 15:08:40

标签: mysql sum

我正在尝试使用另一个表中的和来简单更新表,但由于某种原因,它只更新了一行。以下是表格中的相关信息:

游戏

gameplayer|points
----------------
John      |5
Jim       |3
John      |3
Jim       |4

playercareer

playercareername|playercareerpoints
-----------------------------------
John            |0
Jim             |0

现在最终,我希望在运行更新后,最后一个表看起来像这样:

playercareer

playercareername|playercareerpoints
-----------------------------------
John            |8
Jim             |7

这是我尝试过的只更新第一行的查询:

UPDATE playercareer
SET playercareer.playercareerpoints = 
    (
SELECT 
    SUM(games.points) 
FROM games
    WHERE
     playercareer.playercareername=games.gameplayer
    )

我似乎无法找到答案。提前感谢您的时间和建议!

1 个答案:

答案 0 :(得分:22)

UPDATE playercareer c
INNER JOIN (
  SELECT gameplayer, SUM(points) as total
  FROM games
  GROUP BY gameplayer
) x ON c.playercareername = x.gameplayer
SET c.playercareerpoints = x.total