代码改变世界

sql  not in 一个与直觉相反的问题

2014-12-23 19:16  wangduqiang  阅读(188)  评论(0编辑  收藏  举报

select * from dual where  '1' = 2
select * from dual where  '1' = 1   用来判断一个表达式是不是true

select * from dual where 'wd06000174' not in (select zc.wlccid from c_zzcc zc)

不如这样 (select 1 from c_zzcc zc where  'wd06000174' not in zc.wlccid) 
或 这样 select * from dual where   exists (select 1 from c_zzcc zc where  'wd06000174'  in zc.wlccid) 

 

开始了:

select count(*) from j_yhda yhda where yhda.id in
( select x.yhid  from j_pbxx x where x.pzwz  not in
   (select zc.wlccid from c_zzcc zc where zc.wlccid  )
)这个sql看着没错.但是是错的
正确应该这样写
select count(*) from j_yhda yhda where yhda.id in
( select x.yhid  from j_pbxx x where x.pzwz  not in
   (select zc.wlccid from c_zzcc zc where zc.wlccid is not null )
)

 

原因是这样:

比如  select x.*  from j_pbxx x where   x.pzwz  not in('111',null);
not in 后面的表达式中的结果里不能有null 
如上面的sql  如果是not in('111') 的话能查出来结果. 但 not in('111',null) 就查不出结果.这与常识不同, 因为这里oracle中 null是等于所有值的

 

这个问题没注意到的话会有这样的问题.有个值分明是不在某个表达式的结果中的(这个表达式的结果中有null)  但就是查不出来这个值.
所以呢用not in时候最好限制一下not null