本文介绍了SQL NOT IN 不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有两个数据库,一个保存库存,另一个包含主数据库记录的子集.I have two databases, one which holds the inventory, and another which contains a subset of the records of the primary database.以下 SQL 语句不起作用:The following SQL statement is not working:SELECT stock.IdStock ,stock.DescrFROM [Inventory].[dbo].[Stock] stockWHERE stock.IdStock NOT IN (SELECT foreignStockId FROM [Subset].[dbo].[Products]) not in 不起作用.删除 NOT 会给出正确的结果,即两个数据库中的产品.但是,使用 NOT IN 根本不会返回任何结果.The not in does not work. Removing the NOT gives the correct results, i.e. products that are in both databases. However, using the NOT IN is not returning ANY results at all.我做错了什么,有什么想法吗?What am I doing wrong, any ideas?推荐答案SELECT foreignStockIdFROM [Subset].[dbo].[Products]可能返回一个 NULL.如果NOT IN 值列表中存在任何NULL,NOT IN 查询将不会返回任何行.您可以使用 IS NOT NULL 明确排除它们,如下所示.A NOT IN query will not return any rows if any NULLs exists in the list of NOT IN values. You can explicitly exclude them using IS NOT NULL as below.SELECT stock.IdStock, stock.DescrFROM [Inventory].[dbo].[Stock] stockWHERE stock.IdStock NOT IN (SELECT foreignStockId FROM [Subset].[dbo].[Products] WHERE foreignStockId IS NOT NULL)或者改用NOT EXISTS重写.SELECT stock.idstock, stock.descrFROM [Inventory].[dbo].[Stock] stockWHERE NOT EXISTS (SELECT * FROM [Subset].[dbo].[Products] p WHERE p.foreignstockid = stock.idstock)以及具有您希望 NOT EXISTS 的执行计划的语义通常更简单看起来在这里.As well as having the semantics that you want the execution plan for NOT EXISTS is often simpler as looked at here.行为差异的原因归结于SQL 中使用的三值逻辑.谓词可以评估为 True、False 或 Unknown.The reason for the difference in behaviour is down to the three valued logic used in SQL. Predicates can evaluate to True, False, or Unknown.WHERE 子句的计算结果必须为 True 才能返回该行,但是当 NOT IN 时,这是不可能的>NULL 如下所述.A WHERE clause must evaluate to True in order for the row to be returned but this is not possible with NOT IN when NULL is present as explained below.'A' NOT IN ('X','Y',NULL) 等价于 'A' 'X' 和 'A' <>'Y' 和 'A' <>NULL)'A' 'X' = 真'A' 'Y' = 真'A' NULL = 未知True AND True AND Unknown 根据 Unknownrel="noreferrer">三值逻辑的真值表.True AND True AND Unknown evaluates to Unknown per the truth tables for three valued logic.以下链接对各种选项的性能进行了一些额外的讨论.The following links have some additional discussion about performance of the various options.我应该使用 NOT IN、OUTER APPLY、LEFT OUTER JOIN、EXCEPT 或 NOT EXISTS?NOT IN vs. NOT EXISTS vs. LEFT JOIN/IS NULL:SQL Server左外连接 vs NOT EXISTS不存在 vs NOT INShould I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: SQL ServerLeft outer join vs NOT EXISTSNOT EXISTS vs NOT IN 这篇关于SQL NOT IN 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-26 05:29