mysql - 在 MySQL 中缓存行排名?

标签 mysql

我有一个要排序的列,定期更新排名(每天)。我目前在代码中使用它

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/

相关文章:

php - mysql 从数组更新。我想念什么?

php - FLASH、PHP、MySQL 连接

mysql - ER_ACCESS_DENIED_ERROR : When i try to connect to the database on remote server - Node. js

python - MySQL存储随机数据(直接在表中)

java - org.hibernate.QueryException : could not resolve property: is_approved of: com

php - 错误 1054,无法识别第一个选择列

php - MYSQL语法错误1064

php - MYSQL - 查找刚刚添加的记录的ID

mysql - 单个查询中的多个 in select 语句

php - 为什么我一直得到 'array' 作为查询的输出?