如何解决Mysql:获取重复的记录中的下一个和上一个
我的数据库有两列ID和时间戳。
4 1597228600
8 1597228700
12 1597228700
11 1597228800
14 1597228800
9 1597228900
10 1597228900
1 1597228900
2 1597229000
我需要获取给定ID和时间戳按时间戳排序的下一个(上一个)记录。如果时间戳记重复,则应返回具有较高(较低)id的记录。
在示例中,11(1597228800)的Next和Prev记录是14和12。14(1597228800)的Next和Prev记录是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
。
2个子查询返回?
的上一个ID和下一个ID。
请参见demo。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。