分类目录

链接

2012 年 11 月
 1234
567891011
12131415161718
19202122232425
2627282930  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > MySQL, SQL Server > 正文
SQL各种分页方法汇总
MySQL, SQL Server 暂无评论 阅读(1,982)

 

SQL各种分页方法汇总

平常工作,尤其是面试中经常遇到这样一个问题,查询表A中31到40条的记录,ID可能是不连续的。

 

    1. 如果ID连续
      
      
      1. select * from A where ID between 31 and 40

       

    2. 如果ID不连续,提供三种写法
      
      
      1. --两次对表A查询效率较低
      2. select top 10 * from A where ID not in (select top 30 ID from A)

       

      1. --外层查询没有对表A查询,效率大有提高 select top 10 * from (select top 40 * from A order by ID) as t order by t.ID desc
      2.  
      3.  
      4.  
      5. --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
      6.  
      7.  

 

 不知道还有没有其他写法,我在此抛出一块砖 ……

 

 


 

 

不一会儿,就接到几块玉(期待更多的玉):

 

 

@金色海洋(jyk)阳光男孩

 

  1. --如果是海量数据做查询的话,这个是更高效的,这个不错 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
  2.  
  3.  

 

 

       @害怕飞的鸟

 

  1. --这哥们给出了sql2012的新写法,我机器上没装这么前卫的工具,在我老大的机器上测试可行,性能效率暂不明确 SELECT * FROM A Order by ID OFFSET 30 ROWS FETCH NEXT 10 ROWS ONLY
  2.  
  3.  

 

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:SQL各种分页方法汇总 | Bruce's Blog

发表评论

留言无头像?