oracle中null和‘‘的坑

场景

例如type字段有 null、’’、0、1、2、3 几个值,想要筛选出有数据,但是不为3的数据。
语句:

select * from t_user where type is not null 
and type !='3' and type !='' ;

但是发现查不出数据,这就怪了。

排查解决

是因为oracle同字段不支持2个!=吗

一开始以为oracle同字段不支持2个 != ,那么测试下:

select * from t_user where type !='3' and type !='4' ;

发现有结果,同字段2个!=是没问题的。

null和’’

这里只模拟char和varchar2类型,其他的先不考虑。

试下查询

百度了下,oracle的char和varchar类型中,null和’'是有点区别。
继续测试:

select * from t_user where type !=''; -- 查不出结果
select * from t_user where type is not null ; -- 有结果

select * from t_user where type =''; -- 查不出结果
select * from t_user where type is null ; -- 有结果

试下update

那么update可以吗?语句:

update t_user set type ='' where id  =1;
update t_user set type =null where id  =2;
再查一下:
select * from t_user where type is null;
发现''null的结果都能查出来。

也就是说在oracle中,查询’'和null都要用 is null来查。

回到最初问题

那么开始遇到的问题就很好解决了。
要筛选不为null和不为’'的数据,只要一个 is not null 即可。
语句:

select * from t_user where type is not null 
and type !='3' 
-- and type !=''  -- 这个条件查不出任何内容,必须去掉

问题解决。

总结

注:
当类型为char或varchar2时,过滤条件,不要用 =‘’ 或者 !=’’,因为什么都查不出来。
mysql没有此限制。

猜你喜欢

转载自blog.csdn.net/enthan809882/article/details/112511243