最近看下了,我们项目中,当查询历史订单时,分页查询速度较慢。深入学习一下。
查询了很多方式,整理出下面四种方式:
实验对象:订单表(Order_HIS),字段OrderID,InputStartTime,数据量:11813628(千万级)
目的:分页查询,每页50条数据,我要查第500页数据。(根据InputStartTime排序)
分析:第500页数据,也就是要查50*499+1------50*500,也就是24951到25000的数据。
第一种方式(最平常的方式):
select top 50 OrderID,InputStartTime
from [order_HIS] with (nolock) where OrderID not in (
select top 24950 OrderID from [order_HIS] with (nolock) order by InputStartTime
) order by InputStartTime
--4分11秒
第二种方式(使用大于的方式):
select top 50 OrderID,InputStartTime
from [order_HIS] with (nolock) where InputStartTime > (select max(InputStartTime) from (
select top 24950 InputStartTime from [order_HIS] with (nolock) order by InputStartTime) as a) order by InputStartTime
--25秒
第三种方式(使用排序):
select * from (
select top 50 OrderID,InputStartTime from
(
select top 25000 OrderID,InputStartTime from [Order_HIS] with (nolock) order by InputStartTime asc
) a order by a.InputStartTime desc
) b order by b.InputStartTime
--18秒
第四种方式(使用函数row_number(),2005版本之后可用):
select a.OrderID,a.InputStartTime from (
select top 25000 OrderID,InputStartTime,ROW_NUMBER() over (order by InputStartTime) as rownum
from [Order_HIS] with (nolock) ) a where a.rownum>24950
--15秒
通过上面的比较,发现平常经常使用的not in的方式效率最低。。。而且row_number()函数的方法也有版本限制,所以尽量可以使用第二第三张方式。