3

我有一个未按预期工作的查询

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 的情况下正常运行

我的查询可能有什么问题?

4

3 回答 3

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

另请参阅从一个表中选择另一表中不存在的所有行

于 2010-02-02T21:18:05.510 回答
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()
于 2010-02-02T21:25:46.747 回答
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**)

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

于 2015-04-28T18:06:00.577 回答