T-SQL 查询:不在其中的列给出了错误的结果

T-SQL query: where column not in is giving wrong result

我有两个table A和table B,两个table中的公共列是Name, 我想知道 Table A 中不在 table B

中的名称是什么

当我这样做时:

Select Name from A where Name not in (Select Name from B)

我确定 Table A 中有 2 个名字不在 table B

但结果return什么都没有

table A 和 B 中的这些名称列具有相同的数据类型 varchar(50)

所以我将 Name 列和 Insert 的结果复制到一个新的 table 中并执行相同的查询,这次 return 是正确的结果。这可能是什么错误?

示例:

Table A
Name:
Kevin
Dexter
David 
John
Marry

Table B
Name:
Kevin
Dexter
David 

所以查询应该 return 'John', 'Marry' 但是在我原来的 table 中它不是 return 而是 returns 在另一个 table 我创建并插入。

谢谢!

您可能在 B 上有一个 NULL 名称,这使得每一行的 NOT IN 都为假。您应该使用 NOT EXISTS 代替:

SELECT Name 
FROM A 
WHERE NOT EXISTS (SELECT 1 FROM B 
                  WHERE A.Name = B.Name)
SELECT a.Name
FROM TableA a
LEFT JOIN TableB b ON b.Name = a.Name
WHERE b.Name IS NULL

显然是因为 table B 中某些行的值为 NULL。你可以用 EXCEPT

做你想做的事
SELECT Name FROM TableA
EXCEPT
SELECT Name FROM TableB