Mysql NOT IN and NOT EXIST the same?

后端 未结 4 1721
再見小時候
再見小時候 2021-01-12 07:36

I sometimes interchanged the use of NOT IN and NOT EXIST in my sql queries and both yield the same result. Is the logic behind the NOT EXIST

4条回答
  •  -上瘾入骨i
    2021-01-12 08:30

    No, they are not the same. The IN function translates to a series of OR statements. Typically this trips people up when they use a subquery in the IN function and that query returns at least one null value. E.g. Col Not In( Select Foo From Bar ). This compares Col <> Foo for each row. If one of the values of Foo is null, you get Col <> NULL and the entire statement returns false resulting in no rows.

    Exists simply determines if any rows in the subquery are returned (Not Exists being that no rows can be returned). The Select clause is entirely ignored.


    Example:

    Create Table Test ( Id int not null )
    Insert Test ( 1 )
    Insert Test ( 2 )
    Insert Test ( 3 )
    
    Create Table Bar  ( Foo int null )
    Insert Bar ( Null )
    Insert Bar ( 1 )
    Insert Bar ( 2 )
    

    The following will result in no rows since we are effectively doing the comparison of Not( Id = Null Or Id = 1 Or Id = 2 )

    Select Id
    From Test
    Where Id Not In( Select Foo From Bar )
    

    The following however will return one row

    Select Id
    From Test
    Where Not Exists( Select 1 From Bar Where Foo = Id )
    

    In the above query, I will get Id = 3.

提交回复
热议问题