幾種常見的數據庫分頁語句簡述(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 ,不然會有語法錯誤。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM