---说明:案例来自《收获,不止SQL优化》
创建测试数据:
SQL> drop table t1 purge;
SQL> drop table t2 purge;
SQL> create table t1 as select * from dba_objects ;
SQL> create table t2 as select * from dba_objects ;
SQL> update t2 set status='INVALID' WHERE ROWNUM<=10000;
SQL> update t2 set generated='Y' WHERE ROWNUM<=10000;
SQL> update t2 set temporary='Y' WHERE ROWNUM<=10000;
SQL> update t2 set temporary='M' WHERE temporary<>'Y';
SQL> update t2 set temporary='Q' WHERE temporary<>'Y' or temporary<>'M';
SQL> COMMIT;
SQL> set autotrace traceonly
SQL> set linesize 1000
复制
原SQL:
SQL>
select t1.object_name,
t1.object_id,
(select count(*)
from t2
where temporary = 'Y'
and t2.object_id = t1.object_id) CNT_TEMPORARY_Y,
(select count(*)
from t2
where created >= sysdate - 365
and t2.object_id = t1.object_id) CNT_CREATED_NEW,
(select sum(object_id)
from t2
where status <> 'VALUD'
and t2.object_id = t1.object_id) SUM_OBJID_STATUS_V,
(select sum(object_id)
from t2
where generated = 'Y'
and t2.object_id = t1.object_id) SUM_OBJID_GENERATED_Y,
(select sum(object_id)
from t2
where generated = 'M'
and t2.object_id = t1.object_id) SUM_OBJID_GENERATED_M,
(select sum(object_id)
from t2
where generated = 'Q'
and t2.object_id = t1.object_id) SUM_OBJID_GENERATED_Q
from t1
where t1.object_id <= 50;
复制
case when改造后的SQL:
with w_t2 as
(select
t2.object_id,
count(case when t2.temporary='Y' then 1 end ) CNT_TEMPORARY_Y,
count(case when created >=sysdate-365 then 1 end ) CNT_CREATED_NEW,
sum(case when t2.status<>'VALID' then t2.object_id end ) SUM_OBJID_STATUS_V,
sum(case when t2.generated = 'Y' then t2.object_id end ) SUM_OBJID_GENERATED_Y,
sum(case when t2.generated = 'M' then t2.object_id end ) SUM_OBJID_GENERATED_M,
sum(case when t2.generated = 'Q' then t2.object_id end ) SUM_OBJID_GENERATED_Q
from t2
group by t2.object_id)
select t1.object_name,t1.object_id,w_t2.* from t1,w_t2
where t1.object_id=w_t2.object_id
and t1.object_id<=50;
复制
结论:SQL改写后T2表访问次数由6次降到1次,逻辑读consistent gets由320100降到2580,性能有所提升。
更多数据库相关学习资料,可以查看我的ITPUB博客,网名chenoracle:
http://blog.itpub.net/29785807/
文章转载自IT小Chen,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
相关阅读
Oracle RAC 一键安装翻车?手把手教你如何排错!
Lucifer三思而后行
555次阅读
2025-04-15 17:24:06
【纯干货】Oracle 19C RU 19.27 发布,如何快速升级和安装?
Lucifer三思而后行
477次阅读
2025-04-18 14:18:38
Oracle SQL 执行计划分析与优化指南
Digital Observer
453次阅读
2025-04-01 11:08:44
XTTS跨版本迁移升级方案(11g to 19c RAC for Linux)
zwtian
451次阅读
2025-04-08 09:12:48
墨天轮个人数说知识点合集
JiekeXu
447次阅读
2025-04-01 15:56:03
【ORACLE】记录一些ORACLE的merge into语句的BUG
DarkAthena
440次阅读
2025-04-22 00:20:37
【ORACLE】你以为的真的是你以为的么?--ORA-38104: Columns referenced in the ON Clause cannot be updated
DarkAthena
416次阅读
2025-04-22 00:13:51
Oracle数据库一键巡检并生成HTML结果,免费脚本速来下载!
陈举超
416次阅读
2025-04-20 10:07:02
Oracle 19c RAC更换IP实战,运维必看!
szrsu
395次阅读
2025-04-08 23:57:08
【活动】分享你的压箱底干货文档,三篇解锁进阶奖励!
墨天轮编辑部
365次阅读
2025-04-17 17:02:24