php - update user score from other tables -
i have few tables each have own scores each user. create trigger add scores each user , put them in field called score in users table.
tables (they have same fields few different ones) : table 1 : {id, user_id, score} table 2 : {id, user_id, score} table 3 : {id, user_id, score} users : {id, name, overall_score}
// overall _score has value , want add score fields other tables one.
to achieve lets first write select query , sum of scores per user 3 given tables , how done
select u.*, y.total users u left join ( select user_id,sum(score) total from( select user_id, score table_1 union select user_id, score table_2 union select user_id, score table_3 )x group x.user_id )y on y.user_id = u.id
here demo http://www.sqlfiddle.com/#!9/6f936/1
now lets convert select update command , as
update users u left join ( select user_id,sum(score) total from( select user_id, score table_1 union select user_id, score table_2 union select user_id, score table_3 )x group x.user_id )y on y.user_id = u.id set u.overall_score = coalesce(y.total,0)
here demo http://www.sqlfiddle.com/#!9/c6993/1
Comments
Post a Comment