in、exists、not in、not exists

目前所知,mysql优化器会自动将in转化为exists相关子查询(除了in常量列表),所以in与exists具有相同的执行计划,
那么,当子查询中出现null值呢?
对于exists,不管子查询是什么值,都返回true或者false,同样,not exists也返回true或者false,所以null值对exists没有什么影响
那么对于in,除了返回true、false之外,还有可能对null返回unknown,但是在过滤器中,unknown的处理方式同false,所以使用in与使用exists会得到相同的结果。
但是,对于not in,总是返回false、unknown,这样导致没有数据满足条件。
现在有两张表,test1、test2,test1是个人信息,test2是订单信息,如下:
test1:


in、exists、not in、not exists_第1张图片
图片发自App

test2:


图片发自App

现在test1有27条数据,test2有4条数据,其中test2中有一条数据的的t1_id字段为空,我现在要查出没有订单数据的个人信息,SQL很简单。
in、exists、not in、not exists_第2张图片
图片发自App

可以看到,not exists可以正常返回我们需要的数据,null值不影响结果。

再来看看not in:


in、exists、not in、not exists_第3张图片
图片发自App

对于not in,没有数据返回,原因上面已解释。

为了避免这种情况,可以在子查询中过滤null值,这样,not in才能得到正确结果。


in、exists、not in、not exists_第4张图片
图片发自App

你可能感兴趣的:(in、exists、not in、not exists)