sqlserver分页查询处理方法小结
本文向大家介绍sqlserver分页查询处理方法小结,需要的朋友可以参考一下,后续再行补充更多的分页查询方法
1:第一种 top + not in
top + not in 作为最常见的分页方法,它的优势在更容易理解,数据量小看不出什么差别,缺点是在数据量大的时候使用not in 会引发整表扫描
示例:
测试结果: 10W数据 7780 25W数据 跑了很久都没跑出来 所以不记录了 50W数据 :同理效率应该也低
--准备测试数据
if OBJECT_ID('tempdb..#YDDQ') is not null begin truncate table #YDDQ drop table #YDDQ end select top 300000 * into #YDDQ from WorkFlowTask --第一种 top + not in --测试结果: 10W数据 7780 25W数据 跑了很久都没跑出来 所以不记录了 50W数据 :同理效率应该也低 declare @starttime1 datetime declare @pageindex1 int declare @pagesize1 int select @pageindex1=5000,@pagesize1=50 set @starttime1=getdate() begin --sql语句 select top @pangesize1 * from #YDDQ where ID not in (select top (select (@pageindex1-1)*@pagesize1) ID from #YDDQ order by SenderTime desc) order by SenderTime desc end select datediff(ms,@starttime1,getdate())
2:第二种 ROW_NUMBER() + between and
使用row_number() 给数据添加序号列,根据序号列进行筛选 效率可行,不过row_number函数是在2005版本之后才提供的
--第二种 ROW_NUMBER() + between and --测试结果:50W 数据 6050ms 30W数据 5453ms 10W数据1860ms --准备测试数据 if OBJECT_ID('tempdb..#YDDQ') is not null begin truncate table #YDDQ drop table #YDDQ end select top 300000 * into #YDDQ from WorkFlowTask declare @starttime datetime declare @pageindex int declare @pagesize int select @pageindex=1000,@pagesize=50 set @starttime=getdate() begin --sql语句 select top 100000 * from (select top 100000 ROW_NUMBER() over(order by Id ) _index ,* from #YDDQ ) A where A._index between (select (@pageindex-1)*@pagesize) and (select @pageindex*@pagesize) end select datediff(ms,@starttime,getdate())