sql case oracle,Oracle case when改写SQL

Oracle case when

改写

SQL

---

说明:案例来自《

收获,不止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;

c25d5154ebd048011d5b56f500a1cd40.png

3cbf12a76d35daab468cb7ae00b1a722.png

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;

3d764ad212110a156a6ac9f65f4117ea.png

d2bfa2b4ba42f664e6d1a1f661a107ae.png

结论:

SQL

改写后

T2

表访问次数由

6

次降到

1

次,逻辑读

consistent gets

320100

降到

2580

,性能有所提升。

欢迎关注我的微信公众号"IT小Chen",共同学习,共同成长!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值