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] ) as b where RowId between 1 and 5;
结果:
(2)取第二页数据
select * from ( select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user] ) as b where 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 ) AS A ) as B where 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 ) as A ) as B where B.RowId>5;
注意:文中SQLServer的AS A这些起别名不能省略。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了