mysql not in 和in

来源:互联网 发布:jquery.js cdn 编辑:程序博客网 时间:2024/06/05 03:33

今天碰到一个需求是处理多表查询后去重的,其中在去重时发现返回结果一直是空的,有点莫名奇妙。重新读了一下sql语句,语句如下:

select attachmentid from mal_attachment where attachmentid not in  (select attachmentid from (select attachmentid from mal_solution union select attachmentid from mal_event_information) as temp     union     select attachmentid from mal_malfunction )  ;


最初我以为是由于not in和的判定条件不对导致的,但是找同事咨询了一下改为in如下:

select attachmentid from mal_attachment where attachmentid in  (select attachmentid from (select attachmentid from mal_solution union select attachmentid from mal_event_information) as temp     union     select attachmentid from mal_malfunction )  ;

就出现了值,对比了一下发现in的结果集是正确的,但not in的结果集是错误的,为此我们又在网上查资料对比子查询的结果发现一个问题,子查询的结果中多了一个null,根据网上的相关资料发现not in和in的判定逻辑除了常规意义上的相反以外对于null的理解也是不同的,举个例子:

select id form aaa where id not in ('1','2',null);
跑完的结果每次肯定都是null不管你有没有1,2.原因其实很简单。null不能参与比较一旦参与返回的一定false而not in的判定条件是<> all那么有一个为false就会导致整个集合的比对全部返回null。

结论:

not In 相当于 <> all,如果 Not In 后面跟的是子查询的话,子查询中只要包含一个 null 的返回值,则会造成
整个 Not in 字句返回空值,结果就是查询不会返回任何结果。
而 in 相当于 =any 的意思,可以有效处理子查询中返回空值的情况,返回正确的结果。

相关连接:

http://www.cnblogs.com/huangshoushi/p/6600082.html