对一组行进行排序

Resorting a group of rows

假设我有以下 table,排名,

|film_id|user_id|rank|
|-------|-------|----|
|1      |1      |2   |
|2      |1      |3   |
|3      |1      |1   |
|1      |2      |2   |
|2      |2      |1   |
|3      |2      |3   |

然后我删除了电影 ID 2

是否有 MySQL 方法在单个查询中重新排列每个用户的剩余电影,例如:

|film_id|user_id|rank|
|-------|-------|----|
|1      |1      |2   |
|3      |1      |1   |
|1      |2      |1   | <- changed from 2 to 1
|3      |2      |2   | <- changed from 3 to 2

为清楚起见进行编辑:我不确定我是否会确切地将其称为公式,但我想要做的就是有一个查询,按排名顺序加载剩余的电影,然后重建排名同样的顺序,而且是连续的。

换句话说,如果删除一行后,用户的排名变成了1,2,4,5,6,我想重建为从1开始连续(1,2,3,4, 5).

谢谢!

将 table 加入到使用 ROW_NUMBER() window 函数重建排名的查询中:

UPDATE tablename t1
INNER JOIN (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY `rank`) rn
  FROM tablename
) t2 ON t2.film_id = t1.film_id AND t2.user_id = t1.user_id
SET t1.`rank` = t2.rn
WHERE t1.`rank` <> t2.rn; -- actually this in not needed 
                          -- as MySql does not perform the update 
                          -- if the current and new values are the same

参见demo