标量子查询

 

标量子查询

ORACLE允许在select子句中包含单行子查询, 使用标量子查询可以有效的改善性能,当使用到外部连接,或者使用到了聚合函数,就可以考虑标量子查询的可能性

1. 取消外部连接的使用

外部连接的做法:

select  a.username, count ( * )   from  all_users a,all_objects b
where  a.username = b.owner( + )
group   by  a.username;

 改成标量子查询的做法:

select  a.username,( select   count ( * from  all_objects b  where  b.owner = a.username) cnt
from  all_users a;

 PS: 两种做法得到的结果会有些许差别,主要在all_objects没有符合条件的行时, 外部连接的count(*)=1,而标量子查询的count(*)结果=0

select  a.username, count ( * ), avg ( object_id from  all_users a,all_objects b
where  a.username = b.owner( + )
group   by  a.username; 

 2. 多个聚合函数的使用技巧

当同时出现count(*)/avg()时,不适合在select子句中调用两次子查询,性能上会受到影响, 可以改用下面两种做法

(1).拼接之后再拆分

select  username,to_number(substr(data, 1 , 10 )) cnt,to_number(substr(data, 11 ))  avg   from
(
select  a.username,( select  to_char( count ( * ), ' fm0000000009 ' ||   avg ( object_id from  all_objects b  where  b.owner = a.username) data
from  all_users a
)

 (2).创建对象类型

create   or   replace  type myType  as  object
(cnt 
number , avg   number );

select  username,a.data.cnt,a.data. avg   from
(
select  username,( select  myType( count ( * ), avg ( object_id ))  from  all_objects b  where  b.owner = a.username) data
from  all_users a
) a;
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值