几种常见SQL分页方式效率比较
分页很重要,面试会遇到。不妨再回顾总结一下。
1.创建测试环境,(插入100万条数据大概耗时5分钟)。
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 --返回总记录数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 * 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 outputexec(@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 --返回总记录数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这么一个版本,看起来很强大,调用:
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 @count1 楼 lily200825 2011-11-09 你应该说明一个前提: 这是微软件的数据库SQL2000 下才有效的SQL。