mysql根据当前数据查上一条,下一条数据

1、如果是id自增,按id比较大小取上一条,下一条就行,简单

 

2、不是id自增,按时间排序的列表数据,用以下sql解决

=====================根据时间排序,查上一条

t_pubservice_content 要查询的表,push_time 为排序的时间字段,where后面的条件要不要都可以,根据自己的业务来,id肯定是要的,代表当前数据
复制代码
select t1.* from(
 select @num:=@num-2 as rownum, tpc.*
 from t_pubservice_content tpc,(select @num:=0) as r
 WHERE tpc.cloumn_id = '1664827884371091458'
 order by push_time desc
) t1,(
    select curNum from(
        select @num2:=@num2-2 as curNum, tpc.*
        from t_pubservice_content tpc,(select @num2:=0) r2
        WHERE tpc.cloumn_id = '1664827884371091458'
        order by push_time desc
    ) t where id = '1666995762037964828'
)t2 where rownum > curNum
order by rownum
limit 1
复制代码

 

 

=====================根据时间排序,查下一条

复制代码
select t1.* from(
 select @num:=@num+1 as rownum, tpc.*
 from t_pubservice_content tpc,(select @num:=0) as r
 WHERE tpc.cloumn_id = '1664827884371091458'
 order by push_time desc
) t1,(
    select curNum from(
        select @num2:=@num2+1 as curNum, tpc.*
        from t_pubservice_content tpc,(select @num2:=0) r2
        WHERE tpc.cloumn_id = '1664827884371091458'
        order by push_time desc
    ) t where id = '1666995661924122631'
)t2 where rownum > curNum
order by rownum
limit 1
复制代码

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @   下课后我要去放牛  阅读(1441)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示