我有这个查询会正确返回属于IN
子句的值,但当我将其更改为NOT IN
时,它不会返回任何内容。
有没有人有任何建议?
select distinct
CAST( w.work_area AS CHAR(4) ) || s.code_id as WATT
from
sys_code s,
work_area_master w
where
s.code_type = '590'
and (
CAST( w.work_area AS CHAR(4)) || s.code_id
)
in (
select substr(misc_flags, 1,6)
from sys_code where code_type = 'STA'
);
答案 0 :(得分:1)
当A可能为NULL时,排除原则(即,A或〜A是重言式)不适用。当存在可空字段时,应用三值loigc并且必须将排除原则修改为(A或~A或A为NULL)。
答案 1 :(得分:1)
SELECT DISTINCT
CAST( w.work_area AS CHAR(4) ) || s.code_id AS what
FROM sys_code s
JOIN work_area_master w ON 1=1
WHERE s.code_type = '590'
AND EXISTS (
SELECT * FROM sys_code xx
WHERE xx.code_type = 'STA'
AND substr(xx.misc_flags, 1,6) = CAST( w.work_area AS CHAR(4)) || s.code_id
);
脚注:我故意使用JOIN ... ON 1=1
语法来引起注意原始查询甚至没有连接条件的事实(除了相关 IN子查询中的那个)
答案 2 :(得分:0)
检查sys_code
和work_area_master
的组合是否有效实际上 JOIN
条件。
同时使用EXISTS
代替IN
来避免NULL
@wilplasser already provided SELECT DISTINCT
CAST( w.work_area AS CHAR(4) ) || s.code_id AS what
FROM sys_code s
JOIN work_area_master w ON EXISTS (
SELECT 1
FROM sys_code x
WHERE x.code_type = 'STA'
AND substr(x.misc_flags, 1,6)
= CAST(w.work_area AS CHAR(4)) || s.code_id
)
WHERE s.code_type = '590' ;
出现问题:
NOT IN
有关NULL
和{{1}}问题的详细说明,请参阅此closely related question on dba.SE。
答案 3 :(得分:-1)
可以包括这样的合并功能:
select distinct CAST( w.work_area AS CHAR(4) ) || s.code_id as WATT
from sys_code s, work_area_master w
where s.code_type = '590'
and (CAST( w.work_area AS CHAR(4)) || s.code_id) in (
select substr(coalesce(misc_flags," "), 1,6)
from sys_code
where code_type = 'STA'
);