sql分页 sql server,oracle,db2,mysql

场景一(假设用户只会浏览前面数十页的情况):

思路:取出 页大小*页数的数据,然后拿去 intStartIndex和intEndIndex直接的数据;
优点: 书写简单,通用,适用于用户只会浏览最初几页的情况
缺点:如果数据量超过千万,读取最后几页时会很慢。
 
【sql server】:
  select top 页大小*页数 * from table1 ; 获得数据,然后通过计算拿对应的数据。
 
【oracle】:
  select * from (select TMP_TAB.*, rownum as RN 
  from (select * from table1) TMP_TAB) WHERE RN<=页大小*页数
 
【db2】:
  select * from table1 fetch first 页大小*页数 rows only
 
【mysql】:
 select * from table1 limit  页大小*页数
注:limit后如果是一个参数则从0开始
 
场景二(用户随意访问具体页):
思路: 取出对应的start和end的页条数
优点:能直接拿取,
缺点:书写复杂,且sql sqrver 必须指定一个主键或排序才能完成分页。
【sql server 2000版本】:需要主键id
 select top 页大小 from table1 where id not in( select top 页大小*(页数-1) id from table1 order by id) order by id
 
【sql server 2005或以上】:需要排序字段
 select * from (select row_number() over (order by id) as rn,* from table1 ) where rn>=页开始 and rn =< 页大小*页数)
【db2】:需要排序字段,比sql2005函数少了个下杠号
select * from (select rownumber() over (order by id) as rn,* from table1 ) where rn>=页开始 and rn =< 页大小*页数)
【oracle】
 select * from (select TMP_TAB.*, rownum as RN 
  from (select * from table1) TMP_TAB where RN<=页大小*页数) WHERE RN>=页开始
【mysql】:
   select * from table1 limit 页开始,页大小
 
 
 
原文地址:https://www.cnblogs.com/xuxian/p/4001545.html