实现rownum获取文章上一条下一条

在网上看到很多对文章上一条和下一条查询描述得比较复杂。动手写了一个简单易懂的。
一、查询出文章列表(可添加查询条件和排序)

select id,title from cms
where publish_state = 1 and cms_type = 2 order by publish_time desc

在这里插入图片描述
二、为列表增加rownum作为比较列,为什么不用id?是因为我们的排序规则是用publish_time ,排序后id并不一定按自增方式排序。

select @i:=@i+1 as rownum,id,title from cms as c,(select @i:=0) as s
where c.publish_state = 1 and c.cms_type = 2 order by c.publish_time desc

在这里插入图片描述

三、把具有rownum列的查询结果作为a,构建相同的查询结果作为b,然后使用a和b进行关联查询,以a定位当前文章的rownum位置,以b来确定大于:下一条(或小于:上一条)a的rownum的数据。

--获取下一条
select b.* from 
(select @i:=@i+1 as rownum,id,title from cms as c,(select @i:=0) as s
where c.publish_state = 1 and c.cms_type = 2 order by c.publish_time desc) as a,
(select @j:=@j+1 as rownum,id,title from cms as c,(select @j:=0) as s
where c.publish_state = 1 and c.cms_type = 2 order by c.publish_time desc) as b
where a.id = 14 and b.rownum > a.rownum order by b.rownum asc limit 1

--获取上一条
select b.* from 
(select @i:=@i+1 as rownum,id,title from cms as c,(select @i:=0) as s
where c.publish_state = 1 and c.cms_type = 2 order by c.publish_time desc) as a,
(select @j:=@j+1 as rownum,id,title from cms as c,(select @j:=0) as s
where c.publish_state = 1 and c.cms_type = 2 order by c.publish_time desc) as b
where a.id = 14 and b.rownum < a.rownum order by b.rownum desc limit 1

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值