null不能参与比较运算符,即与任何数据比较结果都为null,
比较结果分为true、false、null,只有结果为true时候,系统才认为匹配成功并返回记录,
| and null | or null |
true | null | true |
false | false | null |
null | null | null |
in后面可以有null,not in后面不能有null
为什么sql语句中not in后面的结果集如果有null,主查询就查不到记录?
select * from table_a as a where a.id in ( 2, null );
--等同于:
select * from table_a as a where a.id=2 or a.id=null;
当a.id=2判断为true时,那么整个or语句就为ture,判定条件成立,
而当a.id是null时,a.id=2判断为false,判断式“null=null”结果为null,整个or语句就为null,所以null记录并不会被返回。
select * from table_a as a where a.id not in ( 2, null );
--等同于:
select * from table_a as a where a.id<>2 and a.id<>null;
由于null值不能参与比较运算符,即跟任何值比较结果都为null,任何表达式and null,结果都为null,判定条件不成立,查询不出来数据。
想要把null查询出来,
in语句后可以加is null,not in语句中可以用nvl(列名,'替代')。
例如,
select * from table_a as a where a.id in ( 2, 3 ) or a.id is null;
select * from table_a as a where nvl(a.id,'空') not in ( '2', '3', '空');
注意2和3加引号。