SQLServer常用分頁(yè)方式
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
mysql的分頁(yè)是基于limit關(guān)鍵字,oracle的分頁(yè)是基于rownum行號(hào),SQLserver的分頁(yè)在下面進(jìn)行研究,是基于SQLServer2012進(jìn)行的測(cè)試。 0.原來(lái)的SQL的所有數(shù)據(jù)
下面的測(cè)試假設(shè)每頁(yè)都是取5條數(shù)據(jù)。 1.第一種-ROW_NUMBER() OVER()方式(over函數(shù)必須有)(1)取第一頁(yè)數(shù)據(jù) select * from ( select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user] ) as b where RowId between 1 and 5; 結(jié)果:
(2)取第二頁(yè)數(shù)據(jù) select * from ( select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user] ) as b where RowId between 6 and 10; 結(jié)果:
總結(jié): 這種方式采用 RowId BETWEEN 當(dāng)前頁(yè)數(shù)-1*頁(yè)大小+1 and 頁(yè)數(shù)*頁(yè)大小 ,而且包含起始值與結(jié)束值。
補(bǔ)充:這種方式的通用寫法如下: 原來(lái)SQL不能帶order by ,但是可以帶條件。 原來(lái)SQL = select * from [mydb].[dbo].[user] where name like 'name%' 拼接分頁(yè)的模板如下: select * from ( select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from ( 原來(lái)SQL ) AS A ) as B where RowId between 1 and 5;
2.第二種-offset start fetch next page rows only(1)取第一頁(yè) select * from [mydb].[dbo].[user] order by ID offset 0 rows fetch next 5 rows only; 結(jié)果:
(2)取第二頁(yè) select * from [mydb].[dbo].[user] order by ID offset 5 rows fetch next 5 rows only; 結(jié)果:
總結(jié):這種方式的起始值與結(jié)束值計(jì)算方式: offset 頁(yè)號(hào)*頁(yè)大小 rows fetch next 頁(yè)大小 rows only
3.第三種: top 關(guān)鍵字(1)取第一頁(yè) select top 5 * from [mydb].[dbo].[user] where ID not in (select top 0 ID from [mydb].[dbo].[user]); 結(jié)果:
(2)取第二頁(yè) select top 5 * from [mydb].[dbo].[user] where ID not in (select top 5 ID from [mydb].[dbo].[user]); 結(jié)果:
總結(jié):這種方式只用改內(nèi)層的 top就可以了: 內(nèi)層的top后面相當(dāng)于起始值,計(jì)算方式為 (頁(yè)號(hào)-1)*頁(yè)大小。 補(bǔ)充:這種分頁(yè)方式的通用模板如下: 這個(gè)可以加order by和條件 原來(lái)SQL = select * from [mydb].[dbo].[user] where name like 'name%' select top 5 * from ( 原來(lái)SQL ) AS A where ID not in (select top 5 ID from [mydb].[dbo].[user]);
4. ROW_NUMBER() + top 相當(dāng)于上面1和3的結(jié)合使用(1)取第一頁(yè) select top (5) * from (select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user]) as A where A.RowId>0; 結(jié)果: (2)取第二頁(yè) select top (5) * from (select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user]) as A where A.RowId>5; 結(jié)果:
總結(jié):這種方式比較通用, 第一個(gè) top 里面的值 相當(dāng)于 頁(yè)大小,第二個(gè)rowID>起始值,起始值計(jì)算方式為 (頁(yè)號(hào)-1)*頁(yè)大小 補(bǔ)充:這種分頁(yè)方式的通用模板如下: 這種方式原來(lái)的SQL也不用加排序語(yǔ)句 原來(lái)SQL = select * from [mydb].[dbo].[user] where name like 'name%' select top (5) * from ( select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from ( 原來(lái)SQL ) as A ) as B where B.RowId>5;
注意:文中SQLServer的AS A這些起別名不能省略。 ?轉(zhuǎn)自https://www.cnblogs.com/qlqwjy/p/10305188.html 該文章在 2025/5/9 9:27:00 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |