在项目中,我们经常遇到或用到分页,那么在大数据量(百万级以上)下,哪种分页算法效率最优呢?我们不妨用事实说话。
测试环境
硬件:CPU 酷睿双核T5750 内存:2G
软件:Windows server 2003 + Sql server 2005
OK,我们首先创建一数据库:data_Test,并在此数据库中创建一表:tb_TestTable
按 Ctrl+C 复制代码按 Ctrl+C 复制代码然后我们在数据表中插入2000000条数据:
1
--插入数据2
setidentity_inserttb_TestTableon3
declare@countint4
set@count=15
while@count<=20000006
begin7
insertintotb_TestTable(id,userName,userPWD,userEmail)values(@count,'admin','admin888','lli0077@yahoo.com.cn')8
set@count=@count+19
end10
setidentity_inserttb_TestTableoff
我首先写了五个常用存储过程:
1,利用select top 和select not in进行分页,具体代码如下:
1
createprocedureproc_paged_with_notin--利用selecttopandselectnotin2
(3
@pageIndexint,--页索引4
@pageSizeint--每页记录数5
)6
as7
begin8
setnocounton;9
declare@timediffdatetime--耗时10
declare@sqlnvarchar(500)11
select@timediff=Getdate()12
set@sql='selecttop'+str(@pageSize)+'*fromtb_TestTablewhere(IDnotin(selecttop'+str(@pageSize*@pageIndex)+'idfromtb_TestTableorderbyIDASC))orderbyID'13
execute(@sql)--因selecttop后不支技直接接参数,所以写成了字符串@sql14
selectdatediff(ms,@timediff,GetDate())as耗时15
setnocountoff;16
end
2,利用select top 和 select max(列键)
1
createprocedureproc_paged_with_selectMax--利用selecttopandselectmax(列)2
(3
@pageIndexint,--页索引4
@pageSizeint--页记录数5
)6
as7
begin8
setnocounton;9
declare@timediffdatetime10
declare@sqlnvarchar(500)11
select@timediff=Getdate()12
set@sql='selecttop'+str(@pageSize)+'*Fromtb_TestTablewhere(ID>(selectmax(id)From(selecttop'+str(@pageSize*@pageIndex)+'idFromtb_TestTableorderbyID)asTempTable))orderbyID'13
execute(@sql)14
selectdatediff(ms,@timediff,GetDate())as耗时15
setnocountoff;16
end
3,利用select top和中间变量--此方法因网上有人说效果最佳,所以贴出来一同测试
1
createprocedureproc_paged_with_Midvar--利用ID>最大ID值和中间变量2
(3
@pageIndexint,4
@pageSizeint5
)6
as7
declare@countint8
declare@IDint9
declare@timediffdatetime10
declare@sqlnvarchar(500)11
begin12
setnocounton;13
select@count=0,@ID=0,@timediff=getdate()14
select@count=@count+1,@ID=casewhen@count<=@pageSize*@pageIndexthenIDelse@IDendfromtb_testTableorderbyid15
set@sql='selecttop'+str(@pageSize)+'*fromtb_testTablewhereID>'+str(@ID)16
execute(@sql)17
selectdatediff(ms,@timediff,getdate())as耗时18
setnocountoff;19新闻热点
疑难解答