mysql sqlserver分页_SQLServer常用分页方式
mysql的分頁是基于limit關鍵字,oracle的分頁是基于rownum行號,SQLserver的分頁在下面進行研究,是基于SQLServer2012進行的測試。
0.原來的SQL的所有數據
下面的測試假設每頁都是取5條數據。
1.第一種-ROW_NUMBER() OVER()方式(over函數必須有)
(1)取第一頁數據
select * from(select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user])asbwhere RowId between 1 and 5;
結果:
(2)取第二頁數據
select * from(select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user])asbwhere RowId between 6 and 10;
結果:
總結: 這種方式采用? ? RowId BETWEEN 當前頁數-1*頁大小+1? and 頁數*頁大小? ?,而且包含起始值與結束值。
補充:這種方式的通用寫法如下:?原來SQL不能帶order by ,但是可以帶條件。
原來SQL =? ? ?select * from [mydb].[dbo].[user] where name like 'name%'
拼接分頁的模板如下:
select * from(select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from(
原來SQL
)ASA
)asBwhere RowId between 1 and 5;
2.第二種-offset start fetch next page rows only
(1)取第一頁
select * from [mydb].[dbo].[user] order by ID offset 0 rows fetch next 5 rows only;
結果:
(2)取第二頁
select * from [mydb].[dbo].[user] order by ID offset 5 rows fetch next 5 rows only;
結果:
總結:這種方式的起始值與結束值計算方式:offset 頁號*頁大小 rows fetch next 頁大小 rows only
3.第三種: top 關鍵字
(1)取第一頁
select top 5 * from [mydb].[dbo].[user]
where ID not in (select top 0 ID from [mydb].[dbo].[user]);
結果:
(2)取第二頁
select top 5 * from [mydb].[dbo].[user]
where ID not in (select top 5 ID from [mydb].[dbo].[user]);
結果:
總結:這種方式只用改內層的 top就可以了:? 內層的top后面相當于起始值,計算方式為? (頁號-1)*頁大小。
補充:這種分頁方式的通用模板如下:?這個可以加order by和條件
原來SQL =?select * from [mydb].[dbo].[user] where name like 'name%'
select top 5 * from(
原來SQL
)AS A where ID not in (select top 5 ID from [mydb].[dbo].[user]);
4.ROW_NUMBER() + top 相當于上面1和3的結合使用
(1)取第一頁
select top (5) * from (select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user]) as A where A.RowId>0;
結果:
(2)取第二頁
select top (5) * from (select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user]) as A where A.RowId>5;
結果:
總結:這種方式比較通用, 第一個 top 里面的值 相當于 頁大小,第二個rowID>起始值,起始值計算方式為? (頁號-1)*頁大小
補充:這種分頁方式的通用模板如下:?這種方式原來的SQL也不用加排序語句
原來SQL =?select * from [mydb].[dbo].[user] where name like 'name%'
select top (5) * from(select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from(
原來SQL
)asA
)as B where B.RowId>5;
注意:文中SQLServer的AS A這些起別名不能省略。
總結
以上是生活随笔為你收集整理的mysql sqlserver分页_SQLServer常用分页方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 数据目录迁移_MySQL数据
- 下一篇: linux搭建宝塔重启mysql_宝塔面