Mysql 查询当前数据上一条和下一条的记录


获取当前文件上一条与下一条记录的原理是上一条的sql语句,从news表里按从大到小的顺序选择一条比当前ID小的新闻,下一条的sql语句,从news表里按从小到大的顺序选择一条比当前ID大的新闻。

如果ID是主键或者有索引,可以直接查找:

 

方法1:

 

[sql]  view plain  copy
 
  1. 1.select * from table_a where id = (select id from table_a where id < {$id} order by id desc limit 1);   
  2. 2.select * from table_a where id = (select id from table_a where id > {$id} order by id asc limit 1);  


方法2:

 

 

[sql]  view plain  copy
 
    1. 1.select * from table_a where id = (select max(id) from table_a where id < {$id});   
    2. 2.select * from table_a where id = (select min(id) from table_a where id > {$id});  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM