试存Oracle储过程时,发现产品表中许多列的值可能为null,导致not exists产生结果与所期不符
测试如下
--构建两个同样表结构的表
SQL> desc t_null_column;
Name Type Nullable Default Comments
---- ------- -------- ------- --------
A INTEGER Y
B INTEGER Y
C INTEGER Y
SQL> desc t_null_column_2;
Name Type Nullable Default Comments
---- ------- -------- ------- --------
A INTEGER Y
B INTEGER Y
C INTEGER Y
--b列为null
SQL> select * from t_null_column;
A B C
--------------------------------------- --------------------------------------- ---------------------------------------
1 2
SQL> select * from t_null_column_2;
A B C
--------------------------------------- --------------------------------------- ---------------------------------------
1 2
--如下sql本意是想查询完全不在t_null_column_2表中的t_null_column表的记录,我想的是不返回记录才对,结果返回了记录
SQL> select tc.* from t_null_column tc where not exists (select 1 from t_null_column_2 tc2 where tc.a=tc2.a and tc.b=tc2.b and tc.c=tc2.c);
A B C
--------------------------------------- --------------------------------------- ---------------------------------------
1 2
--对上述的sql进行修正,对null列b进行nvl变更,这下结果符合期望
SQL> select tc.* from t_null_column tc where not exists (select 1 from t_null_column_2 tc2 where tc.a=tc2.a and nvl(tc.b,1)=nvl(tc2.b,1) and tc.c=tc2.c);
A B C
--------------------------------------- --------------------------------------- ---------------------------------------
小结:1,null相当可怕,一定要深入理解,不然会犯大错误
2,null与null是不相等,即null=null的结果是false,而非true