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这些起别名不能省略。

 

转载于:https://www.cnblogs.com/qlqwjy/p/10305188.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值