[Oracle]高效的PL/SQL程式設計(二)–標量子查詢

來源:互聯網
上載者:User
 

標量子查詢

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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.