mysql根据id更新语句,MYSQL更新语句以按每个ID补余排名

I was trying to implement a query, that for each userid, rank the score and backfill the rank field, so that

id | score | rank

1 | 100 | 0

1 | 200 | 0

1 | 300 | 0

2 | 100 | 0

2 | 200 | 0

3 | 200 | 0

will become

id | score | rank

1 | 100 | 3

1 | 200 | 2

1 | 300 | 1

2 | 100 | 2

2 | 200 | 1

3 | 200 | 1

However, in my case, how can I do the 'group by id' for each id?

解决方案

It might not be the prettiest way, but you can easily do something like:

set @rank = 0;

set @prev = 0;

select id, score, IF (id = @prev, @rank := @rank + 1, @rank := 1), @prev := id

from scores

order by id, score;

I guess you want the update statement as well, and that would be:

set @rank = 0;

set @prev = 0;

update scores

set rank = IF(id = @prev, @rank := @rank + 1, @rank := 1),

id = (@prev := id)

order by id, score;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值