用left join 優化標量子查詢
多次訪問同乙個表時,盡量不用標量子查詢
select s.sid,
s.sname,
s.shot,
s.stype,
(select a.aid from a where a.aid =s.aids) aid,
(select a.aname from a where a.aid =s.aids) aname,
(select a.atime from a where a.aid =s.aids) aatime
from s;
可以看到,在標量子查詢中對a表訪問了三次,而且關聯條件一樣,直接改為left join的方式
select s.sid,s.sname,s.type,s.shot,a.aid,a.anme,a.aatime
from s
left join a on(a.aid=s.aids);
再看下面的例子,當標量子查詢中有聚合時的改寫
select d.department_id,
d.department_name,
d.location_id,
nvl((select
sum(e.salary)from hr.employees e
where e.department_id = d.department_id),0) as sum_sal
from hr.departments d;
改寫時,要先彙總,後關聯
select d.department_id,
d.department_name,
d.location_id,
nvl (e.sum_sal,0) as sum_sal
from hr.departments d
left
join (select e.department_id,sum(e.salary)as sum_sal
from hr.employees e
group
by e.department_id) e
on (e.department_id = d.department_id);
選自《oracle 查詢優化改寫技巧與案例》 有教無類 落落 著
SQL查詢和優化(三)
給查詢結果排序 select empno,ename,hredate from emp where deptno 10 order by hiredate asc 也可以這樣寫 select empno,ename,hredate from emp where deptno 10 orderby3 ...
SQL查詢和優化(五)
一 插入新記錄 建立測試表,各列都有預設值。create table test c1 varchar2 10 defaut 預設1 c2 varchar2 10 defaut 預設2 c3 varchar2 10 defaut 預設3 c4 date default sysdate 新增資料如下 i...
SQL查詢和優化(十一)
不等連線的標量子查詢改寫 前面的例子中,標量子詢查中都是等值的關聯條件,能直接改為left join 或者彙總後再用left join,但遇到不等連線怎麼辦呢?select a.licenceid,a.data source,a.street,select min contdata from ct ...