简体   繁体   English

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

[英]Mysql: Get next and previous in duplicated records

My database has two columns ID and Timestamp.我的数据库有两列 ID 和 Timestamp。

4  1597228600
8  1597228700
12 1597228700
11 1597228800
14 1597228800
9  1597228900
10 1597228900
1  1597228900
2  1597229000

I need to get next (previous) record of the given id and timestamp ordered by timestamp.我需要获取按时间戳排序的给定 id 和时间戳的下一个(上一个)记录。 If the timestamp has duplicates, the record with higher(lower) id should be returned.如果时间戳有重复,则应返回具有较高(较低)id 的记录。

In the example Next and Prev records of the 11(1597228800) are 14 and 12. Next and Prev records of the 14(1597228800) are 1 and 11.在示例中,11(1597228800) 的 Next 和 Prev 记录是 14 和 12。14(1597228800) 的 Next 和 Prev 记录是 1 和 11。

I tried to use CASE condition with subquery, but this solution has issues我尝试将 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

I think that this will do:我认为这会做:

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
  ) 
)

Replace ?更换? with the id that you want to search for.使用您要搜索的id
The 2 subqueries return the ids of the previous and the next id of ? 2 个子查询返回?的前一个和下一个 id 的 id . .
See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM