SQL“NOT IN”由于某种原因不起作用..?

时间:2012-11-19 10:20:37

标签: sql sql-server

以下SQL语句无效:

SELECT  stock.IdStock
        ,stock.Descr       
FROM    [Inventory].[dbo].[Stock] stock
WHERE   stock.IdStock NOT IN
        (SELECT foreignStockId FROM
         [Subset].[dbo].[Products])

2 个答案:

答案 0 :(得分:4)

可能会返回NULL。尝试

SELECT  stock.IdStock
        ,stock.Descr       
FROM    [Inventory].[dbo].[Stock] stock
WHERE   stock.IdStock NOT IN
        (SELECT foreignStockId FROM
         [Subset].[dbo].[Products]
         WHERE foreignStockId IS NOT NULL )

我通常使用NOT EXISTS进行此类查询

SELECT stock.idstock,
       stock.descr
FROM   [Inventory].[dbo].[Stock] stock
WHERE  NOT EXISTS (SELECT *
                   FROM   [Subset].[dbo].[Products] p
                   WHERE  p.foreignstockid = stock.idstock)

答案 1 :(得分:2)

最有可能

SELECT foreignStockId FROM
         [Subset].[dbo].[Products]

查询返回至少一个NULL值

尝试EXISTS

SELECT  stock.IdStock
        ,stock.Descr       
FROM    [Inventory].[dbo].[Stock] stock
WHERE   NOT EXISTS
        (SELECT * FROM [Subset].[dbo].[Products] 
         where stock.IdStock =foreignStockId )