Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql:在重复记录中获取下一个和上一个_Mysql_Performance - Fatal编程技术网

Mysql:在重复记录中获取下一个和上一个

Mysql:在重复记录中获取下一个和上一个,mysql,performance,Mysql,Performance,我的数据库有两列ID和Timestamp 4 1597228600 8 1597228700 12 1597228700 11 1597228800 14 1597228800 9 1597228900 10 1597228900 1 1597228900 2 1597229000 我需要获得给定id和时间戳的下一条前一条记录,按时间戳排序。如果时间戳有重复项,则应返回具有较低id的记录 在本例中,111597228800的Next和Prev记录分别为14和12。1415972288

我的数据库有两列ID和Timestamp

4  1597228600
8  1597228700
12 1597228700
11 1597228800
14 1597228800
9  1597228900
10 1597228900
1  1597228900
2  1597229000
我需要获得给定id和时间戳的下一条前一条记录,按时间戳排序。如果时间戳有重复项,则应返回具有较低id的记录

在本例中,111597228800的Next和Prev记录分别为14和12。141597228800的下一个和上一个记录是1和11

我尝试将CASE条件用于子查询,但此解决方案存在问题

SELECT id 
FROM tbl 
WHERE timestamp_value >= '1597228800' 
AND id > (case when ( SELECT min(id) min_id FROM tbl WHERE id > 11 AND timestamp_value = 1597228800) is null then 0 else 11 end) 
ORDER BY timestamp_value
LIMIT 1

我认为这样做可以:

select t.* 
from tablename t 
cross join (select * from tablename where id = ?) i
where t.id in (
  (
    select id from tablename 
    where (id < i.id and timestamp = i.timestamp) or timestamp < i.timestamp
    order by timestamp desc, id desc limit 1
  ),  
  (
    select id from tablename 
    where (id > i.id and timestamp = i.timestamp) or timestamp > i.timestamp
    order by timestamp, id limit 1
  ) 
)
替换?使用要搜索的id。 这两个子查询返回?的上一个id和下一个id的id?。
请参见。

14是11的下一条记录。说明:14和11条记录具有相同的时间戳,因此具有相同时间戳的id较高的记录是下一条记录,在当前示例中为14。您的MySql版本是什么?MySql版本是5.7,因此如果所有时间戳都相等,那么我们只需按id排序即可?@是的。但在本例中,一些ID较低的记录具有较高的时间戳,因此我不能将ID用作ORDER BY语句中的第二个参数。