[sql查询当前数据上一条和下一条记录]SQL查询当前数据上一条和下一条的记录

更新时间:2017-12-08    来源:Mssql    手机版     字体:

【www.bbyears.com--Mssql】

mssqlserver查询方法

其实我做了最简的就是如下写法

 代码如下

上一条记录的SQL语句:

select top 1 * from news where newsid

下一条记录的SQL语句:

select top 1 * from news where newsid>id order by newsid ASC


另一种写未能

id是指当前数据news_id参数


方法一:

 代码如下


string preSql = "select top 1 * from news where news_id < " + id + " order by news_id DESC"

string nextSql = "select top 1 * from news where news_id > " + id + " order by news_id ASC"


方法二:

 代码如下


string preSql = "select * from [news] where news_id = (select MAX(news_id) from [news] where news_id<" + id + ")";
string nextSql = "select * from [news] where news_id = (select MIN(news_id) from [news] where news_id>" + id + ")";

mysql查询上一条与下一条的办法

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

 代码如下   1.select * from table_a where id = (select id from table_a where id < {$id} order by id desc limit 1);
2.select * from table_a where id = (select id from table_a where id > {$id} order by id asc limit 1);

方法2:

 代码如下   1.select * from table_a where id = (select max(id) from table_a where id < {$id});
2.select * from table_a where id = (select min(id) from table_a where id > {$id});

其他更优的暂时还没想出来

本文来源:http://www.bbyears.com/shujuku/37614.html

热门标签

更多>>

本类排行