侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

sql分页查询几种写法

数据库  /  管理员 发布于 5年前   490

关于SQL语句分页,网上也有很多,我贴一部分过来,并且总结自己已知的分页到下面,方便日后查阅

1.创建测试环境,(插入100万条数据大概耗时5分钟)。

create database DBTestuse DBTest --创建测试表create table pagetest(id int identity(1,1) not null,col01 int null,col02 nvarchar(50) null,col03 datetime null) --1万记录集declare @i intset @i=0while(@i<10000)begin insert into pagetest select cast(floor(rand()*10000) as int),left(newid(),10),getdate() set @i=@i+1end

2.几种典型的分页sql,下面例子是每页50条,198*50=9900,取第199页数据。

--写法1,not in/top

select top 50 * from pagetestwhere id not in (select top 9900 id from pagetest order by id)order by id

--写法2,not exists

select top 50 * from pagetestwhere not exists(select 1 from (select top 9900 id from pagetest order by id)a where a.id=pagetest.id)order by id

--写法3,max/top

select top 50 * from pagetestwhere id>(select max(id) from (select top 9900 id from pagetest order by id)a)order by id

 --写法4,row_number()

select top 50 * from(select row_number()over(order by id)rownumber,* from pagetest)awhere rownumber>9900 select * from(select row_number()over(order by id)rownumber,* from pagetest)awhere rownumber>9900 and rownumber<9951 select * from(select row_number()over(order by id)rownumber,* from pagetest)awhere rownumber between 9901 and 9950

--写法5,在csdn上一帖子看到的,row_number() 变体,不基于已有字段产生记录序号,先按条件筛选以及排好序,再在结果集上给一常量列用于产生记录序号

select *from ( select row_number()over(order by tempColumn)rownumber,* from (select top 9950 tempColumn=0,* from pagetest where 1=1 order by id)a)bwhere rownumber>9900

3.分别在1万,10万(取1990页),100(取19900页)记录集下测试。

测试sql:

declare @begin_date datetimedeclare @end_date datetimeselect @begin_date = getdate()<.....YOUR CODE.....>select @end_date = getdate()select datediff(ms,@begin_date,@end_date) as '毫秒'

1万:基本感觉不到差异。

10万:

4.结论:

1.max/top,ROW_NUMBER()都是比较不错的分页方法。相比ROW_NUMBER()只支持sql2005及以上版本,max/top有更好的可移植性,能同时适用于sql2000,access。

2.not exists感觉是要比not in效率高一点点。

3.ROW_NUMBER()的3种不同写法效率看起来差不多。

4.ROW_NUMBER() 的变体基于我这个测试效率实在不好。原帖在这里 http://topic.csdn.net/u/20100617/04/80d1bd99-2e1c-4083-ad87-72bf706cb536.html

PS.上面的分页排序都是基于自增字段id。测试环境还提供了int,nvarchar,datetime类型字段,也可以试试。不过对于非主键没索引的大数据量排序效率应该是很不理想的。

5.简单将ROWNUMBER,max/top的方式封装到存储过程。

ROWNUMBER():ALTER PROCEDURE [dbo].[Proc_SqlPageByRownumber]( @tbName VARCHAR(255),   --表名 @tbGetFields VARCHAR(1000)= '*',--返回字段 @OrderfldName VARCHAR(255),  --排序的字段名 @PageSize INT=20,    --页尺寸 @PageIndex INT=1,    --页码 @OrderType bit = 0,    --0升序,非0降序 @strWhere VARCHAR(1000)='',  --查询条件 --@TotalCount INT OUTPUT   --返回总记录数)AS-- =============================================-- Author:  allen (liyuxin)-- Create date: 2012-03-30-- Description: 分页存储过程(支持多表连接查询)-- Modify [1]: 2012-03-30-- =============================================BEGIN DECLARE @strSql VARCHAR(5000) --主语句 DECLARE @strSqlCount NVARCHAR(500)--查询记录总数主语句 DECLARE @strOrder VARCHAR(300) -- 排序类型 --------------总记录数--------------- IF ISNULL(@strWhere,'') <>''    SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where 1=1 '+ @strWhere ELSE SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName  --exec sp_executesql @strSqlCount,N'@TotalCout int output',@TotalCount output --------------分页------------ IF @PageIndex <= 0 SET @PageIndex = 1 IF(@OrderType<>0) SET @strOrder=' ORDER BY '+@OrderfldName+' DESC ' ELSE SET @strOrder=' ORDER BY '+@OrderfldName+' ASC ' SET @strSql='SELECT * FROM  (SELECT ROW_NUMBER() OVER('+@strOrder+') RowNo,'+ @tbGetFields+' FROM ' + @tbName + ' WHERE 1=1 ' + @strWhere+' ) tb  WHERE tb.RowNo BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND ' +str(@PageIndex*@PageSize) exec(@strSql) SELECT @TotalCountEND

  

public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, Int32 Size, object Value)  {   return MakeParam(ParamName, DbType,Size, ParameterDirection.Input, Value);  }  public static SqlParameter MakeOutParam(string ParamName, SqlDbType DbType)  {   return MakeParam(ParamName, DbType, 0, ParameterDirection.Output, null);  }  public static SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)  {   SqlParameter param;   if (Size > 0)    param = new SqlParameter(ParamName, DbType, Size);   else    param = new SqlParameter(ParamName, DbType);   param.Direction = Direction;   if (!(Direction == ParameterDirection.Output && Value == null))    param.Value = Value;   return param;  }  /// <summary>  /// 分页获取数据列表及总行数  /// </summary>  /// <param name="tbName">表名</param>  /// <param name="tbGetFields">返回字段</param>  /// <param name="OrderFldName">排序的字段名</param>  /// <param name="PageSize">页尺寸</param>  /// <param name="PageIndex">页码</param>  /// <param name="OrderType">false升序,true降序</param>  /// <param name="strWhere">查询条件</param>  public static DataSet GetPageList(string tbName, string tbGetFields, string OrderFldName, int PageSize, int PageIndex, string strWhere)  {   SqlParameter[] parameters = {      MakeInParam("@tbName",SqlDbType.VarChar,255,tbName),      MakeInParam("@tbGetFields",SqlDbType.VarChar,1000,tbGetFields),       MakeInParam("@OrderfldName",SqlDbType.VarChar,255,OrderFldName),       MakeInParam("@PageSize",SqlDbType.Int,0,PageSize),       MakeInParam("@PageIndex",SqlDbType.Int,0,PageIndex),       MakeInParam("@OrderType",SqlDbType.Bit,0,OrderType),       MakeInParam("@strWhere",SqlDbType.VarChar,1000,strWhere),      // MakeOutParam("@TotalCount",SqlDbType.Int)      };   return RunProcedure("Proc_SqlPageByRownumber", parameters, "ds");  }

调用:

public DataTable GetList(string tbName, string tbGetFields, string OrderFldName, int PageSize, int PageIndex, string strWhere, ref int TotalCount)  {   DataSet ds = dal.GetList(tbName, tbGetFields, OrderFldName, PageSize, PageIndex, strWhere);   TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);   return ds.Tables[0];  }

注意:多表连接时需注意的地方

1.必填项:tbName,OrderfldName,tbGetFields

2.实例:

tbName =“UserInfo u INNER JOIN Department d ON u.DepID=d.ID”  tbGetFields=“u.ID AS UserID,u.Name,u.Sex,d.ID AS DepID,d.DefName”  OrderfldName=“u.ID,ASC|u.Name,DESC” (格式:Name,ASC|ID,DESC)  strWhere:每个条件前必须添加 AND (例如:AND UserInfo.DepID=1 )

Max/top:(简单写了下,需要满足主键字段名称就是"id")

create proc [dbo].[spSqlPageByMaxTop]@tbName varchar(255),  --表名@tbFields varchar(1000),  --返回字段@PageSize int,    --页尺寸@PageIndex int,    --页码@strWhere varchar(1000), --查询条件@StrOrder varchar(255), --排序条件@Total int output   --返回总记录数asdeclare @strSql varchar(5000) --主语句declare @strSqlCount nvarchar(500)--查询记录总数主语句--------------总记录数---------------if @strWhere !=''beginset @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where '+ @strWhereendelsebeginset @strSqlCount='Select @TotalCout=count(*) from ' + @tbNameend--------------分页------------if @PageIndex <= 0begin set @PageIndex = 1endset @strSql='select top '+str(@PageSize)+' * from ' + @tbName + 'where id>(select max(id) from (select top '+str((@PageIndex-1)*@PageSize)+' id from ' + @tbName + ''+@strOrder+')a)'+@strOrder+''exec sp_executesql @strSqlCount,N'@TotalCout int output',@Total outputexec(@strSql)

园子里搜到Max/top这么一个版本,看起来很强大,http://www.cnblogs.com/hertcloud/archive/2005/12/21/301327.html

调用:

declare @count int--exec [dbo].[spSqlPageByRownumber]'pagetest','*',50,20,'','order by id asc',@count outputexec [dbo].[spSqlPageByMaxTop]'pagetest','*',50,20,'','order by id asc',@count outputselect @count

以上就是本文针对sql分页查询几种写法的全部内容,希望大家喜欢。


  • 上一条:
    sql server关键字详解大全(图文)
    下一条:
    SqlServer触发器详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客