我试图实现一个查询,对每个用户ID,对得分进行排名并回填排名字段,以便
id | score | rank
1 | 100 | 0
1 | 200 | 0
1 | 300 | 0
2 | 100 | 0
2 | 200 | 0
3 | 200 | 0
将成为
id | score | rank
1 | 100 | 3
1 | 200 | 2
1 | 300 | 1
2 | 100 | 2
2 | 200 | 1
3 | 200 | 1
我在这里看到了类似的问题 MySQL update statement to store ranking positions
但是,在我的情况下,我怎样才能通过ID'每个id?
答案 0 :(得分:1)
它可能不是最漂亮的方式,但您可以轻松地执行以下操作:
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;
我想你也想要更新语句,那就是:
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;