【问题标题】:How can I make a stored procedure to update one column in one table based on the order of rows from another table?如何创建一个存储过程来根据另一个表中的行顺序更新一个表中的一列?
【发布时间】:2015-10-24 02:24:09
【问题描述】:

我有两张桌子

用户:

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,基于 pointsawards,然后他们的 rankcountry_rank 分别基于 points 的顺序(即rank 1 将是拥有最多points 的用户)?

我考虑过制作一个 PHP 脚本并使用 crontab 偶尔调用它,这样只会在 PHP 中选择信息并进行数学运算等,但对于我的用例来说,存储过程似乎更实用。

【问题讨论】:

  • 你能提供一个小提琴吗?你试过什么?
  • 根据选择的列进行切换。
  • 表Awards中没有时间戳栏吗?在您的示例中,积分是否授予用户 1、10? 30?还是 10+30? (你没有把预期的结果说清楚)
  • @Used_By_Already 奖励的积分数量取决于执行的操作,可以是任何数量。
  • 谢谢你,但请重新阅读评论。 您的样本期望得到什么结果?您的期望是您没有在问题中说明,还有另一个问题。奖项表中是否有时间戳(或任何日期/时间值)?

标签: mysql stored-procedures multiple-columns multiple-tables


【解决方案1】:
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;

【讨论】:

    猜你喜欢
    • 2011-11-25
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 2020-12-14
    相关资源
    最近更新 更多