简体   繁体   中英

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.

I want a totalscore property(which contains the sum of all previous score values) in my profiles table. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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