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

用with 优化复杂SQL,开始时成果显著,然后却开销增加巨大
一个复杂报表,由6个Union组成
...1
union
...2
union
...3
union
...4
union
...5
union
...6
union
...7
1-7的每个SQL,里面都有3个一样的where条件
from factory f , worker_group wg ,  prod
..
where ...
and f.met in ('E1','E8') 
and wg.code  not in ('A1','A6','A7') 
and prod.code !='Active'


优化技术是使用with
with t9
as (
select * form factory  where met in ('E1','E8')
) f,

t10 (
select * form worker_group  where wg.code  not in ('A1','A6','A7') 

后,发现cost从972,086降到456,983 优化效果明显

然后,继续优化
with t1 as
(
select * from prod  where code !='Active'
),
T9
.....



结果发现 cost不降低反而升到843,455了

为什么啊?


------解决方案--------------------
with背后是使用临时表的
会不会是空间压力,导致多次pass
加大临时表或使用TTG试试