select * from A where cc in (select cc from B)性能
select * from A where exists(select cc from B where cc=A.cc)spa
--1.性能的考慮此時就按子表大主表小用exist,子表小主表大用in的原則就能夠.
--2.寫法的不一樣, exist的where條件是: "...... where exist (..... where a.id=b.id)"
--in的where條件是: " ...... where id in ( select id .... where a.id=b.id)"原理
exists作爲where 條件時,是先對where 前的主查詢詢進行查詢,而後用主查詢的結果一個一個的代入exists的查詢進行判斷,若是爲真則輸出當前這一條主查詢的結果,不然不輸出select
好比數據
以下:
表A
ID NAME
1 A1
2 A2
3 A3
表B
ID AID NAME
1 1 B1
2 2 B2
3 2 B3
表A和表B是一對多的關係 A.ID --> B.AID
SELECT ID , NAME FROM A WHERE EXISTS (SELECT * FROM B WHERE A.ID = B.AID)
執行結果爲
1 A1
2 A2
緣由能夠按照以下分析
SELECT ID , NAME FROM A WHERE EXISTS (SELECT * FROM B WHERE B.AID = 1)
-->SELECT * FROM B WHERE B.AID = 1有值返回真因此有數據
SELECT ID , NAME FROM A WHERE EXISTS (SELECT * FROM B WHERE B.AID = 2)
-->SELECT * FROM B WHERE B.AID = 2有值返回真因此有數據
SELECT ID , NAME FROM A WHERE EXISTS (SELECT * FROM B WHERE B.AID = 3)
-->SELECT * FROM B WHERE B.AID = 3無值返回真因此沒有數據
NOT EXISTS 就是反過來
SELECT ID , NAME FROM A WHERE NOT EXIST (SELECT * FROM B WHERE A.ID = B.AID)
執行結果爲
3 A3查詢