MYSQL 更新语句以按每个 ID 回填排名
MYSQL update statement to backfill ranking by each id
我试图实现一个查询,即针对每个用户 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 执行 'group by id'?
这可能不是最漂亮的方式,但您可以轻松地执行以下操作:
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;
我试图实现一个查询,即针对每个用户 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 执行 'group by id'?
这可能不是最漂亮的方式,但您可以轻松地执行以下操作:
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;