码迷,mamicode.com
首页 > 数据库 > 详细

3种SQL语句分页写法

时间:2015-08-27 00:23:14      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

在开发中经常会使用到数据分页查询,一般的分页可以直接用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 当前页*页大小

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

3种SQL语句分页写法

标签:

原文地址:http://www.cnblogs.com/Agan2213/p/4761266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!