简体   繁体   English

如何使存储过程根据另一个表中的行顺序更新一个表中的一列?

[英]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 )?我如何制作一个存储过程来根据来自awardspoints更新用户的总points ,然后根据points的顺序分别更新他们的rankcountry_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.

相关问题 如何根据一个表中的值选择另一个表中的行并对其排序? - How can I select and order rows from one table based on values contained in another? 根据另一个表中的行数更新一个表中的MySQL列 - Update MySQL column in one table based on the number of rows in another table 如何将行从一个MySQL表复制到另一个表并基于变量更新值之一 - How do I copy rows from one MySQL table to another and update one of the values based on a variable 根据另一个表的列排序一个表 - Order one table based on column of another table 如何使用存储过程更新另一个表中的所有列和行 - How to update all columns and rows from another table with a stored procedure Thymeleaf如何根据另一个表中的值显示一个表中的列 - Thymeleaf How can I display a column from one table based on a value from another table 如何使用联接基于另一个表中的行从一个表中获取mysql行? - How can I use joins to fetch mysql rows from one table based on rows that are found in another? 根据另一个表的值更新一个表的列值 - Update column value of one table based on values from another table 如何从一个表中选择行并按另一表中一列的总和对其进行排序? - How to select rows from one table and order it by the sum of a column from another table? 如何使用基于公共参数的另一个表中的值更新一个表中的行 - How to update rows of one table with values from another table based on common parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM