当前位置: 数据库>sqlserver
查询31到40之间数据的方法总结
来源: 互联网 发布时间:2014-08-29
本文导语: sql问题:查询表A中31到40条的记录,ID可能是不连续的。 如果ID连续 代码如下: select * from A where ID between 31 and 40 如果ID不连续,提供三种写法 代码如下: --两次对表A查询效率较低 select top 10 * from A where ID not in (select top 30 ID from ...
sql问题:查询表A中31到40条的记录,ID可能是不连续的。
如果ID连续
代码如下:
select * from A where ID between 31 and 40
如果ID不连续,提供三种写法
代码如下:
--两次对表A查询效率较低
select top 10 * from A where ID not in (select top 30 ID from A)
select top 10 * from A where ID not in (select top 30 ID from A)
--外层查询没有对表A查询,效率大有提高
select top 10 * from (select top 40 * from A order by ID) as t order by t.ID desc
--ROW_NUMBER()函数效率更高,sqlserver2005以及以上版本中才可以使用
select * from (select ROW_NUMBER() over(order by ID) as 'sequence',A.* from A ) as t where t.sequence between 31 and 40
朋友们提供的方法:
@金色海洋(jyk)阳光男孩
代码如下:
--如果是海量数据做查询的话,这个是更高效的,这个不错
select top 10 * from A where id in
(select top 10 id from (select top 40 id from A order by ID desc) as t order by t.ID )
order by A.ID desc
select top 10 * from A where id in
(select top 10 id from (select top 40 id from A order by ID desc) as t order by t.ID )
order by A.ID desc
@害怕飞的鸟
代码如下:
--这哥们给出了sql2012的新写法,我机器上没装这么前卫的工具,在我老大的机器上测试可行,性能效率暂不明确
SELECT * FROM A Order by ID OFFSET 30 ROWS FETCH NEXT 10 ROWS ONLY
SELECT * FROM A Order by ID OFFSET 30 ROWS FETCH NEXT 10 ROWS ONLY
还有没有其它方法,大家可以进 脚本学堂 QQ群:161228069 进行交流。