zoukankan      html  css  js  c++  java
  • SqlServer中offset..fetch 的使用问题

    好久没更新了,最近忙的很,也生病了,重感冒,555~~~

    早上抽的一丝空闲,来讲讲SqlServer中的分页问题。其实用过了多种数据库,分页这问题已经是老生常谈的问题了。不管是开发什么类型的网站,只要是包含检索功能的,不外乎会涉及到分页的问题。

    比如Oracle中的分页:

    select * from (select a.*,rownum rc from 表名 where rownum<=endrow) a where a.rc>=startrow

    select a1.* from (select student.*,rownum rn from student) a1 where rn between startpage and endpage;(使用较多)

    DB2中的分页:

    Select * from (select rownumber() over() as rc,a.* from (select * from 表名 order by 列名) as a) where rc between startrow and endrow

    MySQL中的分页:(感觉是所有数据库中最简单而且写法统一的了)

    select * from table WHERE … LIMIT 10; #返回前10行
    select * from table WHERE … LIMIT 0,10; #返回前10行
    select * from table WHERE … LIMIT 10,20; #返回第10-20行数据

    而针对SqlServer中的分页有多种:

    常用的是用到了row_number()函数,但是只支持SqlServer2005及以上版本

    select top pagenum * from (select row_number()over(order by id)rownumber,* from a)a1 where rownumber>startpage

    select * from (select row_number()over(order by id)rownumber,* from a) a1 where rownumber>startpage and rownumber<endpage+1

    select * from (select row_number()over(order by id)rownumber,* from a) a1 where rownumber between startpage+1 and endpage

    还有这种:

    select top pagenum * from a where not exists (select 1 from (select top 30 id from a order by id)a1 where a1.id=a.id) order by id

    但是我想说的是被好多人所不关注的一种分页方法:

    select * from 表 order by id OFFSET PageIndex*pagenum ROWS FETCH next pagenum rows only

    这种方法是不是很简单,但是这个只有在SQL Server 2012及以上版本中才能使用,无论是从逻辑读取数还是响应时间实际执行行数等关键参数看,SQL Server 2012提供的OFFSET/FETCH NEXT分页方式都比Row_Number()方式有了较大的提升。

    注意:使用该方法必须使用order by ,不然会有语法错误。

  • 相关阅读:
    [JSOI2015]最小表示
    [洛谷2002]消息扩散
    [洛谷1726]上白泽慧音
    [CodeVS2822]爱在心中
    [POJ2186]Popular Cows
    [洛谷1991]无线通讯网
    [CQOI2009]跳舞
    [洛谷1342]请柬
    [USACO07JAN]Balanced Lineup
    [NOIp2003提高组]神经网络
  • 原文地址:https://www.cnblogs.com/timePasser-leoli/p/7837623.html
Copyright © 2011-2022 走看看