[英]T-SQL query: where column not in is giving wrong result
I have two table A and table B, the common column in both table is Name, I want to know what are name in Table A that is not in table B 我有两个表A和表B,两个表中的公共列都是Name,我想知道表A中不在表B中的名称是什么
when I do: 当我做:
Select Name from A where Name not in (Select Name from B)
I am sure there are 2 name in Table A that is not in table B 我确信表A中有2个名称不在表B中
but the result returns nothing 但结果什么都没有
These name column in table A and B has the same datatype varchar(50)
表A和B中的这些名称列具有相同的数据类型varchar(50)
so I copy the result of Name column and Insert into a new table and do the same query, and this time it returns the right result. 所以我将Name列的结果和Insert复制到一个新表中并执行相同的查询,这次它返回正确的结果。 what bug could this be? 这会是什么bug?
example: 例:
Table A
Name:
Kevin
Dexter
David
John
Marry
Table B
Name:
Kevin
Dexter
David
So the query should return 'John'
, 'Marry'
but it doesn't return in my original table, but it returns in another table I create and insert. 所以查询应该返回'John'
, 'Marry'
但它不会在我的原始表中返回,但它会在我创建和插入的另一个表中返回。
Thanks! 谢谢!
You probably have a NULL
name on B
, this makes the NOT IN
false for every row. 您可能在B
上有一个NULL
名称,这使得每行的NOT IN
false。 You should use NOT EXISTS
instead: 您应该使用NOT EXISTS
代替:
SELECT Name
FROM A
WHERE NOT EXISTS (SELECT 1 FROM B
WHERE A.Name = B.Name)
Obviously it is because of NULL value on some rows in table B. You can do what you want with EXCEPT
显然,这是因为表B中某些行的NULL值。您可以使用EXCEPT
SELECT Name FROM TableA
EXCEPT
SELECT Name FROM TableB
SELECT a.Name
FROM TableA a
LEFT JOIN TableB b ON b.Name = a.Name
WHERE b.Name IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.