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()解析函數效率比較高寫。

 


免責聲明!

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



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