MYSQL update statement to backfill ranking by each id

元气小坏坏 提交于 2019-12-11 06:17:59

问题


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

I saw a similar question here MySQL update statement to store ranking positions

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


回答1:


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;


来源:https://stackoverflow.com/questions/38620515/mysql-update-statement-to-backfill-ranking-by-each-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!