Why MYSQL IN keyword not considering NULL values

前端 未结 6 2004
夕颜
夕颜 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:25

    @Michael Buen ' s answer was the right answer for my case, but let me simplify why.

    @Michael says in his post:


    Error not in ('Timeout','Connection Error');

    is semantically equivalent to:

    Error <> 'TimeOut' AND Error <> 'Connection Error'

    Rules about null comparison applies to IN too. So if the value of Error is NULL, the database can't make the expression true.

    And in [1] I found this sentence which confirms his most important statement for understanding why IN fails with NULL. In the specifications ("specs") in [1] you will: "If one or both arguments are NULL, the result of the comparison is NULL, except for the NULL-safe <=> equality comparison operator."

    So yeah, the thing is that sadly Mysql gets lost in such a case. I think Mysql designers shouldn't have done this, because when I compare 2 to NULL, Mysql SHOULD be able to see they are DIFFERENT, and not simply throwing mistaken results. For example, I did:

    select id from TABLE where id not in (COLUMN WITH NULLS);
    

    then it throws EMPTY results. BUT. If I do

    select id from TABLE where id not in (COLUMN WITH OUT NULLS);
    

    it shows the right result. So when using the IN operator, you must filter out the NULLS. This is not a desired behavior for me as a user, but it's documented in the specifications in [1]. I think that languages and technology should be simpler, in the sense that you should be able to DEDUCE without the need of reading the specs. And truly, 2 is DIFFERENT from NULL, I should be the one in charge of controlling and taking care of mistakes of a higher level of abstraction, but MySQL SHOULD throw a FALSE result when comparing NULL with a specific value.

    References for the specs: [1] http://dev.mysql.com/doc/refman/5.6/en/type-conversion.html

提交回复
热议问题