我有一个我要排序的专栏,定期更新排名(每日)。我目前在代码中使用它
get all rows from table order by column
rank = 1
foreach row in table
update row's rank to rank
rank++
这会对MySQL中的每一行进行更新。有更有效的方法吗?
答案 0 :(得分:4)
使用带连接的更新:
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;