Why MYSQL IN keyword not considering NULL values

前端 未结 6 2009
夕颜
夕颜 2020-12-06 05:40

I am using the following query:

select count(*) from Table1 where CurrentDateTime>\'2012-05-28 15:34:02.403504\' and Error not in (\'Timeout\',\'Connectio         


        
6条回答
  •  粉色の甜心
    2020-12-06 06:40

    IN returns a trivalent BOOLEAN (which accepts NULL as a value). NOT IN returns the trivalent negation of IN, and negation of NULL is a NULL.

    Imagine we have a table with all numbers from 1 to 1,000,000 in id and this query:

    SELECT  *
    FROM    mytable
    WHERE   id IN (1, 2, NULL)
    

    or its equivalent:

    SELECT  *
    FROM    mytable
    WHERE   id = ANY
                 (
                 SELECT  1
                 UNION ALL
                 SELECT  2
                 UNION ALL
                 SELECT  NULL
                 )
    

    The predicate returns TRUE for 1 and 2 and NULL for all other values, so 1 and 2 are returned.

    In its oppposite:

    SELECT  *
    FROM    mytable
    WHERE   id NOT IN (1, 2, NULL)
    

    , or

    SELECT  *
    FROM    mytable
    WHERE   id <> ALL
                 (
                 SELECT  1
                 UNION ALL
                 SELECT  2
                 UNION ALL
                 SELECT  NULL
                 )
    

    , the predicate returns FALSE for 1 and 2 and NULL for all other values, so nothing is returned.

    Note that boolean negation not only changes the operator (= to <>), but the quantifier too (ANY to ALL).

提交回复
热议问题