【Oracle】当条件中存在空值时,同时将空值和非空值的结果查询出来

【Oracle】当条件中存在空值时,同时将空值和非空值的结果查询出来

如果不是一定要用这个存在空值的条件的话,最好还是不用为好,省的麻烦

正常的查询结果如下

select * from ttt20230705 t where t.code = 'AA'

image

如果一个表的查询条件中数据为空的时候,是不会查询出来这条空值相关的数据

select * from ttt20230705 t where t.code = 'AA' and t.inv = t.inv

image

那么我们可以通过对语句进行处理来让查询语句同时将空值和非空值的结果都查询出来

1、union all

直接将空值和非空值union在一起

select * from ttt20230705 t where t.inv is null and t.code = 'AA'
union all
select * from ttt20230705 t where t.inv is not null and t.code = 'AA'

2、使用nvl作为条件

使用nvl,当条件为空的时候,赋予一个值,两边同时都增加nvl,这样当为空的时候,也会成立

select * from ttt20230705 t where t.code = 'AA' and nvl(t.inv,'999') = nvl(t.inv,'999')

3、使用or作为条件

用or将空与非空的情况拼起来

select * from ttt20230705 t where ((t.code = 'AA' and t.inv is null) or (t.code = 'AA' and t.inv is not null))

4、使用decode作为条件

和nvl一样,在空的时候赋予一个值,当都为空的时候也会成立

select * from ttt20230705 t where t.code = 'AA' and decode(t.inv,'',0,1) = decode(t.inv,'',0,1)
posted @ 2023-07-06 11:34  DbWong_0918  阅读(702)  评论(0编辑  收藏  举报