SQL NOT IN子句

时间:2010-02-02 21:16:52

标签: .net sql tsql sql-server-2005 notin

我的查询无法按预期工作

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()

即使我知道这些ID不在table_x中,Q1也没有返回任何内容 Q2没有NOT IN正确运行

我的查询有什么问题?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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()

答案 2 :(得分: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**)

确保子查询至少包含一个数字。

相关问题