您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/6/23 9:10:35发布20次查看
获取当前文件上一条与下一条记录的原理是上一条的sql语句,从news表里按从大到小的顺序选择一条比当前id小的新闻,下一条的sql语句,从news表里按从小到大的顺序选择一条比当前id大的新闻。
mssqlserver查询方法
其实我做了最简的就是如下写法
 代码如下 复制代码
上一条记录的sql语句:
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
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_idstring 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 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 2.select * from table_a where id = (select min(id) from table_a where id > {$id});
其他更优的暂时还没想出来
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product