標量子查詢
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;