正常我们使用 IN 或 NOT IN 是需要结果中包含某值或者不包含某值
select uuid , num from PROJECT where sysisdelete = '0'
注意num字段中是包含null值的,接下来我需要查询出 num 字段中不包含99的所有数据
select uuid , num from PROJECT where sysisdelete = '0' and num not in '99'
你会发现结果中确实不包含99 但是null值也没有了
这就是有问题的地方,在项目实际使用SQL过程中及时某个字段存在null值但是不代表这条记录无效,当我同时需要这些null记录的时候就不能用 NOT IN 过滤了。
办法:
通过其他非空字段进行过滤,就像我之前查询出来的字段中有 uuid 和 num 两个字段,num 可能为null,uuid非空所以。
select uuid , num from PROJECT where sysisdelete = '0'
and uuid not in
(SELECT uuid from PROJECT where sysisdelete = '0' and num = '99' )
这才是我们想要的结果。
我是用的数据库是达梦,其他数据库如果在使用 IN 或 NOT IN 某个字段时候如果字段存在null值,会存在查询不出结果情况,注意需要 额外增加条件
and '查询的字段' is not null
select uuid , num from PROJECT where sysisdelete = '0'
and num not in '99'
and num is not null