SQL查詢和優化(十三)

2021-08-06 06:38:37 字數 1840 閱讀 7030

標量子查詢與改寫邏輯的一致性

當標量子查詢中有聚合函式時,很多人在改寫時,很喜歡把聚合函式寫在主查詢裡,大概是認為這樣簡單。

select *

from (select * form t1 where col4_1 = '0') a

left

join (select col3_1,

col3_2 coll,

col2,

select

distinct col_1

from t2

where col2_2 = a.col2

and col2_3 <= to_date('2012-09-03','yyyy-mm-dd')

and col2_4 >= to_date('2012-09-03','yyyy-mm-dd'))

from t3 a

where col2_3 <= to_date('2012-09-03','yyyy-mm-dd')

and col2_4 >= to_date('2012-09-03','yyyy-mm-dd'))b

on a.col4 = b.col3_1;

網友在改寫這個查詢時,直接把distinct 放在了主查詢select關鍵字後面

select *

from (select * form t1 where col4_1 = '0') a

left

join (select

distinct a.col3_1,

a.col3_2 coll,

a.col2,

b.col2_1 as col3

from t3 a

join (select *

from t2 b

where b.col2_3 <= to_date('2012-09-03','yyyy-mm-dd')

and b.col2_4 >= to_date('2012-09-03','yyyy-mm-dd')) b

on a.col2 =b.col2_2

and a.col2_3 <= to_date('2012-09-03','yyyy-mm-dd')

and a.col2_4 >= to_date('2012-09-03','yyyy-mm-dd')) b

on a.col4 = b.col3_1;

筆者不贊成這麼改寫,因為改寫之前有很多重複資料 ,改寫之後就沒有了,可以看下面的等價例子

原查詢可以表示為:

select a.job,

a.dept,

(select

distinct dname from dept2 b where b.deptno = a.deptno) as dename,

from emp a

order

by1,2,3;

按上面的方法更改:

select

distinct a.job,

a.deptno,

b.dname

from emp a

left

join dept2 b on b.deptno = a.deptno;

除非確認主查詢沒有重複資料,否則不要這樣改寫,正確的改寫如下:

select a.job,

a.deptno,

b.dname

from emp a

left

join (select dname,deptno from dept2 group

by dname,deptno) b

on b.deptno = a.deptno;

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...