日期:2014-05-17  浏览次数:20691 次

不理解下面两种方式执行速度
假设n1的值从1到1000,没个值存在一条记录,看下面两个查询,可能看起来有点不合理,把一个东西简化了一下,不用讨论合理性

查询1:(t1中有41条记录)
select n1
from
(select n1,n2 from table 1
where n1<42) t1,
where rownum<21
order by n1


查询2:(t1中有140条记录)
select n1
from
(select n1,n2 from table 1
where n1<141) t1,
where rownum<41
order by n1

从结果来看,查询2比查询1的速度快,我个人感觉是在order by的时候需要利用历史表t1的空间。
对于查询1,t1表最开始分配了41行,然后只对其中20行进行排序
对于查询2,t1表最开始分配了140行,然后只对其中40行进行排序
查询1可能由于临时的空间不够,进行order by计算的时候,需要申请新的空间,花费了一定的时间,
而查询2,临时的空间已经足够运行order by计算,所以不用申请新的空间,所以总体时间反而比查询1速度快了,
是这样吗?

------解决方案--------------------

具體的情況,你可以看一下執行計劃。
1:
explain plan for 
select n1
from
(select n1,n2 from table 1
where n1<42) t1,
where rownum<21
order by n1;

select * from table(dbms_xplan.display);

2:
explain plan for 
select n1
from
(select n1,n2 from table 1
where n1<141) t1,
where rownum<41
order by n1;

select * from table(dbms_xplan.display);

看一下兩個的執行代價。