SQL查詢和優化(十一)

2021-08-06 03:20:55 字數 1726 閱讀 3917

不等連線的標量子查詢改寫

前面的例子中,標量子詢查中都是等值的關聯條件,能直接改為left join 或者彙總後再用left join,但遇到不等連線怎麼辦呢?

select a.licenceid,

a.data_source,

a.street,

(select

min(contdata)

from ct

where ct.licenceid = a.licenceid

and ct.data_source = a.data_source

and trunc(contdate) >= a.opendaledate) as mincontdata,

(select

min(buydate)

from ct

where ct.licenceid = a.licenceid

and ct.data_source = a.data_source

and trunc(buydate) >= a.opendaledate) as minbuydate

from a;

要想把兩個量合併,必須要先與a表關聯,這樣才能在取最值前過濾

select a.rowid as rid,

min(case

when trunc(ct.contdate) >= a.opendaledate) then

ct.contdate end)as mincontdate,

min(case

when trunc(ct.buydate) >= a.opendaledate) then

ct.buydate end)as minbuydate

from ct

inner

join a on(ct.licenceid = a.licenceid

and ct.data_source = a.data_source)

group

by a.rowid

到此標量部分搞定,再左聯就可以了

with ct2 as(

select a.rowid as rid,

min(case

when trunc(ct.contdate) >= a.opendaledate) then

ct.contdate end)as mincontdate,

min(case

when trunc(ct.buydate) >= a.opendaledate) then

ct.buydate end)as minbuydate

from ct

inner

join a on(ct.licenceid = a.licenceid

and ct.data_source = a.data_source)

group

by a.rowid)

select a.licenceid,

a.data_source,

a.street,

ct2.mincontdate as mincontdate,

ct2.minbuydate as minbuydate

from a

left

join ct2 on(ct2.rid = a.rowid);

選自《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 優化標量子查詢 多次訪問同乙個表時,盡量不用標量子查詢 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.ai...