美文网首页
MySQL NOT IN的坑——注意null

MySQL NOT IN的坑——注意null

作者: lsyarn | 来源:发表于2019-02-15 10:43 被阅读0次

    近日在使用mysql的not in查询时遇到了一个问题,本来应该有的数据查出来为空。运行的sql如下

    select name from table1 where name not in (select name from table2);
    

    对table说明一下,有一些name存在于table1但是不存在于table2。例如
    table1包含:

    小明
    小红
    

    table2包含:

    小明
    大雄
    

    期望的查询结果应该包含小红,但是查询结果却是!!!
    经过一番google,发现原因是table2的name字段包含了null值。使用如下sql可以他到预期效果:

    select name from table1 where name not in (
      select name from table2 where name is not null
    );
    

    为什么呢?
    原因是not in的实现原理是,对每一个table1.name和每一个table2.name(括号内的查询结果)进行不相等比较(!=)。

    foreach name in table2:
        if table1.name != name:
            continue
        else:
            return false
    return true
    

    而sql中任意!=null的运算结果都是false,所以如果table2中存在一个nullnot in的查询永远都会返回false,即查询结果为空。

    相关文章

      网友评论

          本文标题:MySQL NOT IN的坑——注意null

          本文链接:https://www.haomeiwen.com/subject/xyfpeqtx.html