假设我有以下表格,排名,
|film_id|user_id|rank|
|-------|-------|----|
|1 |1 |2 |
|2 |1 |3 |
|3 |1 |1 |
|1 |2 |2 |
|2 |2 |1 |
|3 |2 |3 |
和I删除电影id2
。
是否有一种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)开始的连续。
谢谢!
将表连接到使用ROW_NUMBER()
窗口函数重建排名的查询:
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