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