[英]How can I make a stored procedure to update one column in one table based on the order of rows from another table?
I have two tables我有两张桌子
Users:用户:
user | name | country | rank | country_rank | points
1 | frank | US | to be determined | to be determined | to be determined
Awards:奖项:
awarded_to | points_awarded
1 | 10
1 | 30
How can I make a stored procedure to update the users total points
based off of the points
from awards
, then their rank
and country_rank
respectively based off of the order of the points
(ie rank
1 would be the user with the most points
)?我如何制作一个存储过程来根据来自
awards
的points
更新用户的总points
,然后根据points
的顺序分别更新他们的rank
和country_rank
(即rank
1 是拥有最多points
的用户)?
I considered making a PHP script and using a crontab to call it occasionally that would just select the info and do the math etc in PHP, but stored procedures seems much more practical for my use-case.我考虑过制作一个 PHP 脚本并使用 crontab 偶尔调用它,它只会选择信息并在 PHP 中进行数学运算等,但是对于我的用例来说,存储过程似乎更实用。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.