在oracle 中in , EXISTS对于空值的处理,会出现失效的情况
建立test01,test02 两张表 col01作为两个表的唯一标识。col02均含有一个空值
使用exists时,发现[5,ta]这一条数据出现了 而这一条数据并不存在test02中。
用in时 ,无法识别null,没有出现[4,null]这样一条数据
select * from test01 t1 where t1.col02 in (select col02 from test02 t2 where t1.col01=t2.col01);
select * from test01 t1 where exists (select col02 from test02 t2 where t1.col01=t2.col01);
再看一下not in , not exists的结果
not exists 出现了空集合,
not in结果符合预期。
select * from test01 t1 where t1.col02 not in (select col02 from test02 t2 where t1.col01=t2.col01);
select * from test01 t1 where not exists (select col02 from test02 t2 where t1.col01=t2.col01);
在书写代码使用exists和in的时候 当是一个已知的固定集合可以使用in 或者 not in
当涉及一个子查询时应尽量使用join 进行关联判断,避免出现结果失真。当不可避免使用的时候,应当尽可能使用in的语法;
本文已在mysql,pgsql,oracle进行了测试不再累述