`
yanghuidang
  • 浏览: 910537 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

[Oracle]高效的PL/SQL程序设计(二)--标量子查询

 
阅读更多

本系列文章导航

[Oracle]高效的PL/SQL程序设计(一)--伪列ROWNUM使用技巧

[Oracle]高效的PL/SQL程序设计(二)--标量子查询

[Oracle]高效的PL/SQL程序设计(三)--Package的优点

[Oracle]高效的PL/SQL程序设计(四)--批量处理

[Oracle]高效的PL/SQL程序设计(五)--调用存储过程返回结果集

[Oracle]高效的PL/SQL程序设计(六)--%ROWTYPE的使用

标量子查询

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

1. 取消外部连接的使用

外部连接的做法:

selecta.username,count(*)fromall_usersa,all_objectsb
wherea.username=b.owner(+)
groupbya.username;

改成标量子查询的做法:

selecta.username,(selectcount(*)fromall_objectsbwhereb.owner=a.username)cnt
fromall_usersa;

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

selecta.username,count(*),avg(object_id)fromall_usersa,all_objectsb
wherea.username=b.owner(+)
groupbya.username;

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

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

(1).拼接之后再拆分

selectusername,to_number(substr(data,1,10))cnt,to_number(substr(data,11))avgfrom
(
selecta.username,(selectto_char(count(*),'fm0000000009')||avg(object_id)fromall_objectsbwhereb.owner=a.username)data
fromall_usersa
)

(2).创建对象类型

createorreplacetypemyTypeasobject
(cnt
number,avgnumber);

selectusername,a.data.cnt,a.data.avgfrom
(
selectusername,(selectmyType(count(*),avg(object_id))fromall_objectsbwhereb.owner=a.username)data
fromall_usersa
)a;

博文来源:http://blog.csdn.net/huanghui22/archive/2007/04/30/1593263.aspx

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics