浅析mysql中的not in中的结果为空

 在使用mysql中发现not in中的结果集并不是in的差集的时候,且not in的结果集是空的..感觉很郁闷..所以就来找原因,

原因就是not in中不能有null值.

return;

想看原因的往下走...

下图中:

#1和#3的结果集相同;

#2和#4的结果集不同.其中#2的结果集为空;

#1和#3互为差集;

#2和#4自然就不是差集了....#2是空集.

SELECT a.* from t_car a where a.owner  in (1,2,null);#1
SELECT a.* from t_car a where a.owner not  in (1,2,null);#2
SELECT a.* from t_car a where a.owner  in (1,2);#3
SELECT a.* from t_car a where a.owner not  in (1,2);#4

表t_car

mysql在解析sql语句的时候,会not in 和 in进行sql内部语法解析.其中

not in    等价于  <>all

in         等价于   =any

select * from t_car where owner <> null;#空结果集
select * from t_car where owner <> 2;#结果集不为空
select * from t_car where owner is not null;#结果集不为空

看上面三条sql中.....当出现   <> 与null进行比较时,所得出的结果集就是空....而<>与非null值(2)进行比较时,就会是正常的结果集..

所以.在mysql的语句解析中,我们可以看到判断字段是否为空的条件是

is null和is not null

而我们的in和not in又不会判断你是否为null,sql

会认为都是有值的,所以会用<>比较.而不是is null 和is not null判断..

所以,答案就出在这里了..

猜你喜欢

转载自blog.csdn.net/YoungLee16/article/details/81670764
今日推荐