NOT IN does not produce same results as NOT EXISTS

前端 未结 2 980
滥情空心
滥情空心 2021-01-22 19:27

These are rather basic statements. I have a list of graphics which are linked to items in another table. I want to check how many of the graphics are not in use and can theoreti

2条回答
  •  鱼传尺愫
    2021-01-22 20:08

    That because of NULL value returned from subquery :

    SELECT [GraphicNr], [Graphicfile]
    FROM [dbo].[Graphic]
    WHERE graphicnr NOT IN (SELECT graphicnr FROM dbo.Komp)
    

    This would produce no records or no rows affected because of graphicnr not in (null) which is not desired output.

    So, the NOT EXISTS would not work as the way the IN clause or NOT IN work. It behaves differently then IN or NOT IN clause.

    However, you can prevent this by using IS NOT NULL filter in subquery. But the recommended way is to use NOT EXISTS instead.

提交回复
热议问题