SQL分页查询,纯Top方式和row_number()解析函数的使用及区别

SherlynGilb 8年前

来自: http://www.cnblogs.com/ericli-ericli/p/5177076.html

听同事分享几种数据库的分页查询,自己感觉,还是需要整理一下MS SqlSever的分页查询的。

Sql Sever 2005之前版本:

select top 页大小 *  from 表名  where id not in  (   select top 页大小*(查询第几页-1) id from 表名 order by id  )  order by id

例如:

select top 10 * --10 为页大小  from [TCCLine].[dbo].[CLine_CommonImage]  where id not in  (   --40是这么计算出来的:10*(5-1)   --                    页大小*(查询第几页-1)   select top 40 id from [TCCLine].[dbo].[CLine_CommonImage] order by id  )  order by id

结果为:

Sql Sever 2005及以上版本,多了个分页查询方法:

/*    * firstIndex:起始索引      * pageSize:每页显示的数量    * orderColumn:排序的字段名    * SQL:可以是简单的单表查询语句,也可以是复杂的多表联合查询语句    */    select top pageSize o.* from (select row_number() over(order by orderColumn) as rownumber,* from(SQL) as o where rownumber>firstIndex;

例如:

select top 10 numComImg.* from   ( select row_number() over(order by id asc) as rownumber,* from (select *  FROM [TCCLine].[dbo].[CLine_CommonImage]) as comImg)   as numComImg where rownumber>40

结果:

这两个方法,就仅仅是多了一列 rewnumber 吗?当然不是,来看下内部差别吧:

在两个SQL上,分别加入以下SQL,并使用MS的“包括执行计划”,便于查看执行详情:

SET STATISTICS TIME ON  GO

要执行的SQL:

SET STATISTICS TIME ON  GO  select top 10 numComImg.* from   ( select row_number() over(order by id asc) as rownumber,* from (select *  FROM [TCCLine].[dbo].[CLine_CommonImage]) as comImg)   as numComImg where rownumber>40      SET STATISTICS TIME ON  GO  select top 10 * --10 为页大小  from [TCCLine].[dbo].[CLine_CommonImage]  where id not in  (   --40是这么计算出来的:10*(5-1)   --                    页大小*(查询第几页-1)   select top 40 id from [TCCLine].[dbo].[CLine_CommonImage] order by id  )  order by id

执行之后,查看执行计划:

看得出,两个同样功能的SQL,执行时,使用 row_number() 的,要比是用 纯TOP方式的,查询开销少得多,上图显示 28:72,纯top方式,使用了两次聚集扫描。

再来看下执行时间信息:

row_number()方式的:

纯top方式:

相比之下,还是row_number()解析函数效率比较高写。