zoukankan      html  css  js  c++  java
  • SQL分页查询,纯Top方式和row_number()解析函数的使用及区别

    听同事分享几种数据库的分页查询,自己感觉,还是需要整理一下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()解析函数效率比较高写。

  • 相关阅读:
    Nginx配置文件nginx.conf中文详解
    PHP SOCKET编程 .
    当一个变量只能通过引用传递的时候。
    PHP-Socket-阻塞与非阻塞,同步与异步概念的理解
    PHP里的socket_recv方法解释
    jQuery获取Select选择的Text和 Value
    使用 cacti 批量监控服务器以及其 PHP 运作环境配置
    windows 和 linux 上 循环读取文件名称的区别和方法
    php 在linux 用fopen() 函数打开,file_get_contents(),fread()函数 读取 另外一台服务器映射过来的文件 总是返回false,null的情况。
    【问题解决】小数点前面不显示0的问题
  • 原文地址:https://www.cnblogs.com/ericli-ericli/p/5177076.html
Copyright © 2011-2022 走看看