2011-05-21 120 views
0

檢查其內的多個選擇語句子查詢「不」條件子查詢與多個SELECT語句

EG。

select id from tbl where 
id not in (select id from table1) and 
id not in (select id from table2) and 
id not in (select id from table3) 

,而不是重複「不」條件相同的id,我需要將一次性檢查多個表的子查詢..

請幫助..

+0

你的表面上緊急的問題已經在下面回答..... – 2011-05-21 10:26:36

回答

0

你可以使用一個工會,所以你只要有一個in

select id 
from tbl 
where id not in 
     (
     select id from table1 
     union all select id from table2 
     union all select id from table3 
     ) 

注意:not in不適用於可爲空的列,但我認爲id在此處不可空。

+0

我會有興趣比較查詢計劃與這個答案和我.... – 2011-05-21 14:16:31

1

您所查詢的是更好表現爲:

SELECT id 
FROM tbl t 
LEFT JOIN table1 t1 on t1.id = t.id 
LEFT JOIN table2 t2 on t2.id = t.id 
LEFT JOIN table3 t3 on t3.id = t.id 
WHERE t1.id IS NULL AND t2.id IS NULL AND t3.id IS NULL 
+0

(重新編號你的表,因爲你已經加入table1兩次,而根本沒有表3) – 2011-05-21 10:07:36

+0

謝謝,我是一個可怕的打字員! – 2011-05-21 10:07:58