SQLServer数据分页

一.分页

将一定量的数据进行分页,每一页中定量存储数据

1.top分页查询

比如当前存在于数据库中的一共有40条数据,我们将每10条数据算作一页,那么一共可以分出4页,如果要进行查询的话,只需要使用如下格式即可:

sql 复制代码
--查询第一页
select top 5 * from Student 
--查询第二页
select top 5 * from Student 
where Id not in(1,2,3,4,5,6,7,8,9,10)

注意点:虽然我们一般所使用的Id自增长形式为identity(1,1),即从1开始,每次增长1,但是在我们查询分页时还是要注意Id的自增长形式,避免出错

而从上方的示例中不知道你们有没有发现一个规律,写出来是这样的:

select top 页码 * from 表名

where Id not in(select top 页码*(当前页-1) Id from 表名)

所以正确的分页查询格式应该为:

sql 复制代码
select top 5 * from Student 
where Id not in(select top 0 Id from Student) 
select top 5 * from Student 
where Id not in(select top 5 Id from Student)
select top 5 * from Student 
where Id not in(select top 10 Id from Student)

若是运用了变量,那么就更容易理解了

sql 复制代码
declare @Size int = 5 
declare @Page int = 1 
select top (@Size) * from Student 
where Id not in(select top (@Size * (@Page - 1)) Id from Student) 

只需要修改Page变量(页数),就可以查询到该页的数据了

2.row_number分页查询

格式为:

sql 复制代码
select * from 
(select row_number() over(order by Id) RowId,* from Student) 
where Id between (当前页号-1) * 每页大小 + 1 and 当前页号 * 每页大小 

同样使用到变量进行举例:

sql 复制代码
declare @Size int = 5 
declare @Page int = 1
select * from 
(select row_number() over(order by Id) RowId,* from Student) 
where Id between (@Page-1) * @Size + 1 and @Page * @Size  
相关推荐
rainFFrain13 分钟前
(MySQL)库的操作
数据库·mysql
八股文领域大手子2 小时前
深入理解缓存淘汰策略:LRU 与 LFU 算法详解及 Java 实现
java·数据库·算法·缓存·mybatis·哈希算法
noravinsc2 小时前
django admin 中更新表数据 之后再将数据返回管理界面
数据库·django·sqlite
春风不会绿大地2 小时前
IDEA编写flinkSQL(快速体验版本,--无需配置环境)
sql·flink
Bruce-li__4 小时前
DRF凭什么更高效?Django原生API与DRF框架开发对比解析
数据库·django·sqlite
noravinsc4 小时前
connection.cursor() 与 models.objects.filter
数据库·django·原生查询·orm查询
laimaxgg6 小时前
MySQL复合查询
数据库·mysql
编程在手天下我有6 小时前
Redis 常见问题深度剖析与全方位解决方案指南
数据库·redis·缓存·性能优化·数据持久化·分布式系统
辰哥单片机设计7 小时前
JQ6500语音模块详解(STM32)
数据库·mongodb
阿桨8 小时前
【保姆级教程-Centos7环境下部署mongodb并设置开机自启】
数据库·mongodb·centos