本章节执行计划请自行采集。
1.数据准备
drop table test1;
drop table test2;
create table test1 as select * from dba_objects;
create table test2 as select * from dba_objects;
2.问题SQL
update test1 t1
set t1.object_id=(select max(t2.OBJECT_ID)
from test2 t2
where t1.object_name=t2.OBJECT_NAME)
where exists (select 1
from test2 t
where t1.owner=t.owner);
Update下面跟了两个节点,类似于嵌套循环,表行数都是7万多,还没有索引,当然很慢。
其实,有很多小伙伴肯定说可以改成下面的样子;
update test1 t1
set t1.object_id=(select max(t2.OBJECT_ID)
from test2 t2
where t1.object_name=t2.OBJECT_NAME
and t1.owner=t2.owner)
where exists (select 1
from test2 t
where t1.owner=t.owner
and t1.object_name=t.object_name);
效率和之前类似,也很慢。
3.优化SQL
merge into test1 d
using (select distinct
t2.owner
,t2.object_name
,max(t2.OBJECT_ID) over (partition by t2.object_name) as max_OBJECT_ID
from test2 t2) s
on (d.owner=s.owner
and d.object_name=s.object_name)
when matched then update
set d.object_id=s.max_OBJECT_ID ;