SQL Server - 不在
我需要构建一个查询,根据品牌-型号-序列号组合显示表 1 中但不在表 2 中的记录。
我知道事实上有 4 条记录不同,但我的查询总是返回空白。
SELECT *
FROM Table1 WHERE MAKE+MODEL+[Serial Number] NOT IN
(SELECT make+model+[serial number] FROM Table2)
表1有5条记录。
当我将查询更改为 IN
时,我得到 1 条记录。我做错了什么NOT
?
I need to build a query that will show me records that are in Table 1, but that are not in Table 2, based on the make-model-serial number combination.
I know for fact that there are 4 records that differ, but my query always comes back blank.
SELECT *
FROM Table1 WHERE MAKE+MODEL+[Serial Number] NOT IN
(SELECT make+model+[serial number] FROM Table2)
Table 1 has 5 records.
When I change the query to IN
, I get 1 record. What am I doing wrong with the NOT
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是因为 NOT IN 的工作方式。
为了避免这些令人头疼的问题(并且在许多情况下为了更快的查询),我总是更喜欢 NOT EXISTS:
It's because of the way NOT IN works.
To avoid these headaches (and for a faster query in many cases), I always prefer NOT EXISTS:
您可能最好单独比较字段,而不是连接字符串。
You're probably better off comparing the fields individually, rather than concatenating the strings.
这对我有用,其中
make+model+[serial number]
是一个字段名称That worked for me, where
make+model+[serial number]
was one field name使用 LEFT JOIN 检查右侧是否有空值。
上面的代码将根据 TableA 和 TableB 中的 Id 列来匹配 TableA 和 TableB,然后给出 B 侧为空的行。
Use a LEFT JOIN checking the right side for nulls.
The above would match up TableA and TableB based on the Id column in each, and then give you the rows where the B side is empty.
一个问题可能是,如果品牌、型号或[序列号] 为空,则永远不会返回值。因为带有 null 值的字符串连接总是会导致 null,而 not in () with null 则始终不会返回任何内容。解决方法是使用 IsNull(make, '') + IsNull(Model, '') 等运算符。
One issue could be that if either make, model, or [serial number] were null, values would never get returned. Because string concatenations with null values always result in null, and not in () with null will always return nothing. The remedy for this is to use an operator such as IsNull(make, '') + IsNull(Model, ''), etc.