简体   繁体   English

用一个SQL查询更新总数

[英]updating totals with one sql query

I have a table with players, and a table with profiles. 我有一张桌子,上面有球员,还有一张桌子,上面有个人资料。 Profiles(users) can "claim" players, so that the "profile" field in a player record gets set to the id of the profile. 个人资料(用户)可以“声明”玩家,以便将玩家记录中的“个人资料”字段设置为个人资料的ID。

I want a totalscore property(which contains the sum of all previous score values) in my profiles table. 我想要个人资料表中的totalscore属性(包含所有先前得分值的总和)。 To calculate data commited in the past, i've written the following query: 为了计算过去提交的数据,我编写了以下查询:

UPDATE profiles,players
SET profiles.`totalscore` = profiles.`totalscore` + players.`score`
WHERE players.`profile`=profiles.`id`

However, totalscore gets set to the last found value. 但是,totalscore设置为最后找到的值。 How would i solve this? 我该如何解决?

You have to use group by. 您必须使用分组依据。

UPDATE profiles
inner join (
select profileid,SUM(score) as playersscore
from players
group by
profileid) players
ON players.profileid=profiles.id
SET profiles.totalscore = profiles.totalscore + playersscore

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM