2010-02-02 92 views
3

我預期SQL NOT IN子句

Q1: 
SELECT id, name 
FROM vw_x 
WHERE id NOT IN (select pid from table_x) 
GROUP BY id, name 
Having max(c_date) > GETDATE() 

Q2: 
SELECT id, name 
FROM vw_x 
GROUP BY id, name 
Having max(c_date) > GETDATE() 

Q1不返回任何東西,即使我知道這些ID不是TABLE_X這是行不通的查詢 Q2正常運行,而無需NOT IN

我的查詢有什麼問題?

回答

19

你在表

NULL值試試這個

SELECT id, name 
FROM vw_x 
WHERE id NOT IN (select pid from table_x where pid is not null) 
GROUP BY id, name 
Having max(c_date) > GETDATE() 

或本

SELECT id, name 
FROM vw_x 
WHERE NOT EXISTS (select 1 from table_x where pid = vw_x.id ) 
GROUP BY id, name 
Having max(c_date) > GETDATE() 

參見Select all rows from one table that don't exist in another table

+0

對不對,我正要發佈答案,謝謝:) – 2010-02-02 21:24:08

+0

感謝您的新鏈接,它非常好用 – 2010-02-02 21:26:06

2

有關使用左連接是什麼?

SELECT id, name 
FROM vw_x 
LEFT JOIN table_x on id = pid 
WHERE pid IS NULL 
GROUP BY id, name 
Having max(c_date) > GETDATE() 
0

還有另外一種情況:子查詢可能什麼都不會返回。 如果NOT IN子句返回空列表,SQL Server不能正常工作。我有如下查詢:

select * from table where id not in (select id from tableB where somecondition(x)) 

當子查詢包含一個id列表時,查詢將按預期方式返回數據。但是,當子查詢不返回任何內容時,查詢仍會返回數據,但隨後會卡住。

我改變了查詢以下,並解決了這個問題:

select * from table where id not in (select id from tableB where somecondition(x) **union all select 0**) 

這可以確保子查詢至少包含一個數字。