几种常见的数据库分页语句简述(offset....fetch)

开发的时候遇到一些数据库开发不是很常见的关键字,网上搜索了一下,其实用过了多种数据库,分页这问题已经是老生常谈的问题了。不管是开发什么类型的网站,只要是包含检索功能的,不外乎会涉及到分页的问题。

比如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 pagenumrows only

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

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

猜你喜欢

转载自www.cnblogs.com/mingjianchen/p/12079762.html