我有一个要排序的列,定期更新排名(每天)。我目前在代码中使用它
get all rows from table order by column
rank = 1
foreach row in table
update row's rank to rank
rank++
这对 MySQL 中的每一行进行更新。有没有更有效的方法来做到这一点?
最佳答案
使用连接更新:
set @rank := 0;
update tbl a join
(select id, @rank := @rank + 1 as new_rank from tbl order by col) b
on a.id = b.id set a.rank = b.new_rank;
如果期望有很多行,您将通过对索引表进行连接来获得最佳性能,例如:
set @rank := 0;
create temporary table tmp (id int primary key, rank int)
select id, @rank := @rank + 1 as rank from tbl order by col;
update tbl join tmp on tbl.id = tmp.id set tbl.rank = tmp.rank;
最后,您可以通过完全跳过更新步骤并换入新表(并非总是可行)来使其更快:
set @rank := 0;
create table new_tbl (id int primary key, rank int, col char(10),
col2 char(20)) select id, @rank := @rank + 1 as rank, col, col2
from tbl order by col;
drop table tbl;
rename table new_tbl to tbl;
关于mysql - 在 MySQL 中缓存行排名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2029491/