EXITS 和 IN 的區別:
從效率來看:
1) select * from T1 where exists(select 1 from T2 where T1.a=T2.a) ;
T1數據量小而T2數據量非常大時,T1<<T2 時,1) 的查詢效率高。
2) select * from T1 where T1.a in (select T2.a from T2) ;
T1數據量非常大而T2數據量小時,T1>>T2 時,2) 的查詢效率高。
簡而言之,一般式:外表大,用IN;內表大,用EXISTS。
如果查詢的兩個表大小相當,那么用in和exists差別不大。
如果兩個表中一個較小,一個是大表,則子查詢表大的用exists,子查詢表小的用in:
例如:表A(小表),表B(大表)
1:
select * from A where cc in (select cc from B)
效率低,用到了A表上cc列的索引;
select * from A where exists(select cc from B where cc=A.cc)
效率高,用到了B表上cc列的索引。
相反的
2:
select * from B where cc in (select cc from A)
效率高,用到了B表上cc列的索引;
select * from B where exists(select cc from A where cc=B.cc)
效率低,用到了A表上cc列的索引。
EXISTS與IN的使用效率的問題,通常情況下采用exists要比in效率高,因為IN不走索引,但要看實際情況具體使用:
IN適合於外表大而內表小的情況;EXISTS適合於外表小而內表大的情況。
(4)sql語句中 < any 和 <all 的區別
1、查找年齡比15、16、22、21、17、18、19中任意一個都小的學生記錄就有如下代碼:
select *
from student
where age<any(15,16,22,21,17,18,19)
2、查找年齡比15、16、22、21、17、18、19中任意一個都大的學生記錄就有如下代碼:
select *
from student
where age>any(15,16,22,21,17,18,19)
從上面來看. ANY的意義不就和ALL一樣了.
ANY是小於集合里任何一個.也就是比最小的還小.
ALL比所有的都小.不也是比最小的還小.
二者的區別在哪.用在什么地方會有不同?
