NOT IN Select语句返回0个值

时间:2015-09-09 01:17:17

标签: sql teradata

我有变量ID和代码的数据。示例数据如下所示:

ID   Code
abc  00
def  00
ghi  00
def  23
jkl  00
mno  20 
pqr  24

ID可以包含多个不同代码的值。我试图找出每个ID的所有可能的代码组合(总共有15个)

我的代码:

select id, code from data.test 
where id in (select id from data.test where code = 00 )
and id in ('abc','def','ghi','jkl','mno','pqr') 

工作正常(返回4行)但是这段代码:

select id, code from data.test 
where id not in (select id from data.test where code = 23)
and id in ('abc','def','ghi','jkl','mno','pqr') 

返回0行?它应该返回3行。

我使用的是Teradata SQL Assistant 15.00.0.02版。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

子查询失败的not in的一个原因是因为其中一个值(在您的情况下为id)为NULL。在这种情况下,NOT IN表达式永远不会返回true。解决这个问题的一种方法是:

select id, code
from data.test 
where id not in (select id from data.test where code = 23 and id is not null) and
      id in ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr') 

另一种方法是使用NOT EXISTS

select t.id, t.code
from data.test t
where not exists (select 1 from data.test t2 where t.code = 23 and t2.id = t.id) and
      t.id in ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr')