几种常见SQL分页方式效率比较

转载地址:http://www.cnblogs.com/iamowen/archive/2011/11/03/2235068.html 

分页很重要,面试会遇到。不妨再回顾总结一下。

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

create database DBTest
use DBTest

--创建测试表
create table pagetest

(
id int identity(1,1) not null,
col01 int null,
col02 nvarchar(50) null,
col03 datetime null
)

--1万记录集
declare @i int

set @i=0
while(@i<10000)
begin
insert into pagetest select cast(floor(rand()*10000) as int),left(newid(),10),getdate()
set @i=@i+1
end


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

--写法1,not in/top
select top 50 * from pagetest

where id not in (select top 9900 id from pagetest order by id)
order by id




--写法2,not exists
select top 50 * from pagetest

where 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 pagetest

where 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)a
where rownumber>9900

select * from
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber>9900 and rownumber<9951

select * from
(select row_number()over(order by id)rownumber,* from pagetest)a
where 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
)b
where rownumber>9900

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

测试sql:

declare @begin_date datetime
declare @end_date datetime
select @begin_date = getdate()

<.....YOUR CODE.....>

select @end_date = getdate()
select datediff(ms,@begin_date,@end_date) as '毫秒'

 

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

10万:

100万:

 

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():

create proc [dbo].[spSqlPageByRownumber]
@tbName varchar(255), --表名
@tbFields varchar(1000), --返回字段
@PageSize int, --页尺寸
@PageIndex int, --页码
@strWhere varchar(1000), --查询条件
@StrOrder varchar(255), --排序条件
@Total int output --返回总记录数
as

declare @strSql varchar(5000) --主语句
declare @strSqlCount nvarchar(500)--查询记录总数主语句

--------------总记录数---------------
if @strWhere !=''

begin
set @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where '+ @strWhere
end
else
begin
set @strSqlCount='Select @TotalCout=count(*) from ' + @tbName
end
--------------分页------------
if @PageIndex <= 0

begin
set @PageIndex = 1
end

set @strSql='Select * from (Select row_number() over('+@strOrder+') rowId,'+ @tbFields
+' from ' + @tbName + ' where 1=1 ' + @strWhere+' ) tb where tb.rowId >'+str((@PageIndex-1)*@PageSize)
+' and tb.rowId <= ' +str(@PageIndex*@PageSize)

exec sp_executesql @strSqlCount,N'@TotalCout int output',@Total output
exec(@strSql)

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 --返回总记录数
as

declare @strSql varchar(5000) --主语句
declare @strSqlCount nvarchar(500)--查询记录总数主语句

--------------总记录数---------------
if @strWhere !=''

begin
set @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where '+ @strWhere
end
else
begin
set @strSqlCount='Select @TotalCout=count(*) from ' + @tbName
end
--------------分页------------
if @PageIndex <= 0

begin
set @PageIndex = 1
end

set @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 output
exec(@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 output
exec [dbo].[spSqlPageByMaxTop]'pagetest','*',50,20,'','order by id asc',@count output

select @count

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/547670.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在Eclipse中,用XFire发布web服务

配置及相关说明见http://www.cnblogs.com/xshy3412/archive/2007/09/29/910848.html 仅确定发布xfire需要的最基本的jar activation-1.1.jar commons-logging-1.0.4.jar jdom-1.0.jar jsr173_api-1.0.jar spring-1.2.6.jar stax-utils-20040917.jar wsdl4j-1.6.1.jar wstx-asl-…

BinderHub 使用简介

使用 Binder 將公開的 GitHub Repository 轉換為可互動、可執行程式碼並能在瀏覽器上一鍵啟動的 JupyterHub 伺服器&#xff0c;讓我們可以快速地建造出方便分享的教學環境。 Python 3.6 JupyterLabPython 3.7 Jupyter NotebookR 3.6 JupyterHubR 3.6 RStudio 使用 Binder 與 …

matlab for循环太慢,Matlab中每个for循环迭代的速度降低

我在Matlab中编写了一个while循环&#xff0c;应该使用Matlab中的tic toc延迟在指定的时间间隔内将数组中的每个值从Matlab发送到arduino&#xff0c;然后读取值并将它们存储在变量中并对其进行图形化。while循环的输出随着每次连续的迭代而减慢。我增加了缓冲区大小&#xff0…

Js表单验证整理

1.手机验证[验证13系列和150-159(154除外)、180、185、186、187、188、189几种号码&#xff0c;长度11位] function isMobel(value) { if (/^13\d{9}$/g.test(value) || (/^15[0-35-9]\d{8}$/g.test(value)) || (/^18[05-9]\d{8}$/g.test(value))) { return true; …

Ruby on Rails 實戰聖經阅读(三)

由于是1.8.x&#xff1b;圣经的1.9.3差太多,所以另外按1.8.X来创建hello world 第一個Hello World!! 1. 创建项目rails -d mysql first 2。创建控制器 cd first ruby script/generate controller hello 3.创建交互动作 vi app/controllers/hello_controller.rb 修改为 …

Java简单的返回结果工具类

以下是一个简单的Java工具类&#xff0c;用于返回结果&#xff1a; public class ResultUtil {/*** 返回成功结果* param data 返回的数据* param <T> 数据类型* return Result对象*/public static <T> Result<T> success(T data) {Result<T> result …

Sql自动配置器原理及其说明

简介&#xff1a;Sa设置辅助器设计的初衷是为了抛开繁琐与重复的配置&#xff0c;这种繁琐到了一定程度回使人厌烦&#xff0c;重复到了一种程度让人觉得无趣&#xff0c;为了解决这种厌烦与无趣&#xff0c;她就出现与产生了。底下的原理适用于任何SQL Server版本与运行平台。…

Oracle 日常巡检——数据库基本情况检查

对于线上的业务&#xff0c;Oracle 的 数据库 运行的稳定性和安全性是用户关心的一个至关重要的问题&#xff0c;除了通过监控平台对数据库进行监控以外&#xff0c;还需要定期对数据库进行“体检”&#xff0c;数据库巡检是保障数据库稳定运行的必不可少的辅助手段。 本文将简…

matlab对多个矩阵循环,MATLAB:在不使用循环的情况下提取矩阵的多个部分

有许多方法可以在没有循环的情况下完成此操作.大多数解决方案涉及将向量x和y扩展为更大的索引矩阵,并且可能使用函数REPMAT,BSXFUN或SUB2IND中的一个或多个.可以在here找到用于矩阵索引的良好教程.但是,既然你要求一个优雅的解决方案,这里有一点不寻常.它使用anonymous functio…

路由器ospf动态路由配置

技术原理&#xff1a;Ospd开放式最短路径优先协议。是目前网络中应用最广泛的路由协议之一。属于内部网络路由协议。能够适应各种规模的网络环境&#xff0c;是典型的链路状态协议。Ospf路由协议通过向全网扩散本设备的链路状态信息&#xff0c;使网络中每台设备最终同步一个具…

js常用事件整理—兼容所有浏览器

1.鼠标滚动事件。 说明&#xff1a;返回值 大于0向上滚动&#xff0c;小于0向下滚动。 兼容型&#xff1a;所有浏览器。 代码&#xff1a; /*********************** * 函数&#xff1a;鼠标滚动方向* 参数&#xff1a;event * 返回&#xff1a;滚轮方向[向上&#xff08;大…

Kubernetes 持久化存储 Cephfs

熟悉kubernetes volume的同学应该了解&#xff0c;kubernetes 对volume的提供支持“静态PV”和“动态PV”两种方式。 静态PV&#xff1a;集群管理员创建一些PV&#xff0c;之后便可用于PVC消费。 动态PV&#xff1a;相比静态PV而言&#xff0c;动态PV无需管理员手动创建PV&…

RDIFramework.NET — 系列目录 — 基于.NET的快速信息化系统开发框架

RDIFramework.NET — 基于.NET的快速信息化系统开发框架 — 系列目录RDIFramework.NET&#xff0c;基于.NET的快速信息化系统开发、整合框架&#xff0c;给用户和开发者最佳的.Net框架部署方案。框架简单介绍RDIFramework.NET&#xff0c;基于.NET的快速信息化系统开发、整合框…

Visual Studio项目版本转换器(c#项目版本转换器 v1.0)

Visual Studio项目版本转换器&#xff08;c#项目版本转换器 v1.0&#xff09; 使用截图&#xff1a; 下载地址&#xff1a;http://files.cnblogs.com/stone_w/VsConvert.zip vs转换中文通用版&#xff0c;目前版本只支持c#程序。 功能说明&#xff1a; 1.智能判断当前待转换引…

debian apache php mysql,Debian下配置APACHE2+MYSQL5+PHP5

Loading...如果之前安装过apache, mysql, php,要先删除掉&#xff1a;#apt-get remove --purge apache2.2-common apache2#apt-get remove mysql1. 先安装apache2#apt-get install apache2.2-common apache2#apache2ctl start //启动apache2测试&#xff0c;在我的host os中的I…

基于 Kubernetes 构建企业 Jenkins 持续集成平台

1、部署Jenkins 新建kube-ops 命名空间 $ kubectl create namespace kube-ops 新建Deployment文件(jenkins2.yaml) ---apiVersion: extensions/v1beta1kind: Deploymentmetadata: name: jenkins2 namespace: kube-opsspec: template: metadata: labels: …

TC 配置插件

转载&#xff1a;http://hi.baidu.com/accplaystation/item/07534686f39dc329100ef310 1、插件下载地址&#xff1a;http://www.topcoder.com/tc?moduleStatic&d1applet&d2plugins 一般用下面三个插件&#xff1a;CodeProcessor&#xff08;2.0&#xff09;&#xff0…

WebClient 访问间歇性返回403解决方案

说明&#xff1a;前段时间做的一个项目莫名的返回403的错误&#xff0c;这种情况也多大是程序员最不喜欢的了&#xff0c;没办法先来分析一下错误信息。之前的代码如下&#xff1a; WebClient webclient new WebClient();string u9Str webclient.DownloadString("http:/…

bootstrap select2 php,JS组件Bootstrap Select2使用方法详解

在介绍select组件的时候&#xff0c;之前分享过一篇JS组件中bootstrap multiselect两大组件较量的文章&#xff0c;这两个组件的功能确实很强大&#xff0c;本文分享下select组件的一些用法和特性。一些通用的单选、多选、分组等功能这里就不多做介绍了&#xff0c;multiselect…

恢复Linux系统权限

注意 如果Linux整个系统文件权限都被设置为777&#xff0c;请不要重启系统&#xff0c;因为很多同学认为万能的重启能解决98%的问题。重启后权限就能恢复。但这次请不要重启系统&#xff0c;如果重启系统&#xff0c;系统直接损坏。 解决思路 虽然损坏的服务器没有权限备份&…