我有两张桌子
用户:
user | name | country | rank | country_rank | points
1 | frank | US | to be determined | to be determined | to be determined
奖:
awarded_to | points_awarded
1 | 10
1 | 30
如何根据points
的{{1}},然后分别根据points
和awards
制作存储过程来更新用户总数rank
基于country_rank
的顺序(即points
1将是rank
}用户最多的用户?
我考虑制作一个PHP脚本,并使用crontab偶尔调用它,只需在PHP中选择信息并进行数学运算等,但存储过程似乎对我的用例更实用。
答案 0 :(得分:0)
create temporary table awardsum (user int, total int); #temp
insert into awardsum
select a.awarded_to, sum(a.points_awarded)
from users u
inner join awards a on u.user=a.awarded_to
group by a.awarded_to;
update users
join awardsum on users.user=awardsum.user
set users.points = awardsum.total;
SELECT @row:=0;
UPDATE users
SET rank = (@row:=@row+1)
ORDER BY points desc;
drop table awardsum;