3种SQL语句分页写法

在开发中经常会使用到数据分页查询,一般的分页可以直接用SQL语句分页,当然也可以把分页写在存储过程里,下面是三种比较常用的SQL语句分页方法,下面以每页5条数据,查询第3页为例子:

      第一种:使用not in,select top 方法:

select top 5 * from T_user where ID not in(select top (3-1)*5 id from T_user order by ID)

说明:select top 页大小 [要查询的字段名称] from 表名 where ID not in(select top (当前页数-1)*页大小 id from 表名 order by ID)

  第二种:使用select top ,max方法:

select top 5 * from T_user where(ID>=(select MAX(id)from(select top (3-1)*5+1 ID from T_user order by ID)as t))order by ID
说明:select top 页大小 [要查询的字段名称] from 表名 where(ID>=(select Max(id)from(select top(当前页数-1)*页大小+1) ID from 表名 order by ID)as t)order by ID)

   第三种:如果SQLServer是2005及以上版本,可以使用ROW_NUMBER()函数进行分页:

select * from
(
select *, row_number()over(order by id) as num from T_user 
)as t where t.num between (3-1)*5+1 and 3*5
说明:select * from(select [要查询的字段名称], row_number()over(order by id) as num from 表名 )as t where t.num between (当前页-1)*页大小+1 and 当前页*页大小

  以上三种方法,从效率上讲方法一相对来说比较慢,二和三相差不大。。

转载于:https://www.cnblogs.com/Agan2213/p/4761266.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值