平常工作,尤其是面试中经常遇到这样一个问题,查询表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)
--外层查询没有对表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
- 如果ID连续
@金色海洋(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
@害怕飞的鸟
--这哥们给出了sql2012的新写法,我机器上没装这么前卫的工具,在我老大的机器上测试可行,性能效率暂不明确
SELECT * FROM A Order by ID OFFSET 30 ROWS FETCH NEXT 10 ROWS ONLY
from:http://www.cnblogs.com/wenyang-rio/archive/2012/10/25/2738499.html