[英]MS Access sql using NOT IN
I am working in MS Access 2013 with these two tables. 我正在使用这两个表在MS Access 2013中工作。
t1: t2:
ID ID F1 F2
1 a a
2 1 b a
3 2 b a
I know it is not the most ideal way to do this, but I wrote this query to pull all IDs that dont exist in another table. 我知道这不是执行此操作的最理想方法,但是我编写了此查询来提取所有其他表中不存在的ID。
Select [ID] from table1 WHERE [ID] NOT IN (SELECT ID FROM table2)
The query should return 3, but for some reason this table gives me no results. 查询应该返回3,但是由于某种原因,该表没有任何结果。 When I change the query to this, it gives me 3 as the result. 当我将查询更改为此时,结果为3。
Select [ID] from table1 WHERE [ID] NOT IN (SELECT [ID] FROM table2 WHERE [ID] IS NOT NULL)
I am unsure to why the logic of why the second query works, but the first one returns no results. 我不确定为什么第二个查询起作用的逻辑,但是第一个查询没有返回结果。 When I run the nested query (SELECT [ID] FROM table2) it does not return 3 for either query, so both queries should work. 当我运行嵌套查询(来自table2的SELECT [ID])时,对于任何一个查询都不会返回3,因此这两个查询都应该工作。 Can anyone explain why the first query does not return anything? 谁能解释为什么第一个查询不返回任何内容?
I strongly recommend that you simply forget using not in
with subqueries. 我强烈建议您只是忘记not in
子查询not in
使用。 Instead, use not exists
: 相反,使用not exists
:
Select [ID]
from table1 as t1
where NOT EXISTS (SELECT 1 FROM table2 as t2 WHERE t2.id = t1.id);
As you have learned, not in
has the wrong semantics (ie behavior) when the subquery returns NULL
. 如您所知,当子查询返回NULL
时, not in
具有错误的语义(即行为)。 Instead of trying to make it work, just use NOT EXISTS
. 与其尝试使之工作, NOT EXISTS
使用NOT EXISTS
。 An added bonus is that this readily extends to multiple columns and should use an index if available. 另外一个好处是,它可以很容易地扩展到多列,并且应该使用索引(如果有)。
无法评估Null
值,因此,当查询尝试查看3
是否=
为null
它不知道如何检查,因此不返回任何内容。
这是因为In的工作方式(当然不是Not In)在此问题的答案中有详细说明: SQL“选择不在子查询中的位置”不会返回任何结果
If you insist on using NOT IN, use this (assuming ID can't be negative in table2): 如果您坚持使用NOT IN,请使用以下命令(假设ID在表2中不能为负):
Select ID
from table1
WHERE ID
NOT IN
(
SELECT Nz(ID,-1)
FROM table2
)
Nz converts a Null value to the provided parameter. Nz将Null值转换为提供的参数。 If no parameter is provided, Nz converts to zero or a zero-length string. 如果未提供任何参数,则Nz转换为零或零长度的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.