我有一个复合索引(在“name”VARCHAR(50) 和“ts”TIMESTAMP 列上)。
对于特定记录,我想按时间查找具有相同“名称”(如果存在)的前一条记录。
(当使用低级非关系数据库(例如 D-ISAM)时,这是快速且简单的。)
如何在 MySQL 中执行此操作?
最佳答案
这是一种方法。查找与您要查找的记录具有相同名称
的所有行。然后按 ts
以相反的顺序排序并选择第一个:
select t.*
from table t join
(select * from table t where <record = your record>
) therec
on t.name = therec.name and t.ts < therec.ts
order by t.ts desc
limit 1;
关于mysql - 在 MySQL 中高效获取前一条记录(通过索引),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21481675/