不在子句中不在SQL中工作

问题描述 投票:0回答:3

此查询未返回任何记录:

select abc from table1
where SOEID='A'
and ID in (
  select ID from Table2
  where column1='1234'
  and ID2 in (
    select ID2 from Table3
    where column2='5678'
  )
)
and reject_id not in (
  select reject_ID from error_table
);

但是这个查询会返回记录:

select abc from table1
where SOEID='A'
and ID in (
  select ID from Table2 
  where column1='1234'
  and ID2 in (
    select ID2 from Table3
    where column2='5678'
  )
)
and reject_id not in (
  select reject_ID from error_table  where SOEID='A'
);

所以我想,因为我使用过滤器它返回记录,即这些记录不存在于特定的SOEID中。

所以我查了一下

select * from error_table
where reject_ID ='one record which was returned in the previous query';

这也没有返回任何记录!我在这做错了什么?

我以为因为我使用过滤器查询返回了记录,所以我检查记录而不使用过滤器它没有返回任何记录。

sql oracle
3个回答
2
投票

不要将NOT IN与子查询一起使用。它没有您期望的语义。如果子查询中的任何值返回NULL值,则根本不返回任何行。通常,您只想忽略NULL值。

所以,使用NOT EXISTS代替:

Select abc
from  table1 t1
where SOEID = 'A' and
      ID in (select ID
             from  Table2 
             where column1 = '1234' and
                   ID2 in (select ID2 from Table3 where column2 = '5678')
            ) and
      not exists (select 1
                  from error_table et
                  where t1.reject_id = et.reject_ID and
                        **SOEID='A'**
                 );

0
投票

问题在于这部分:

and ID in (select ID from  Table2 
where column1='1234' and ID2 in (select ID2 from Table3 where column2='5678'))

将其更改为:

and ID in (select ID from  Table2 
where column1='1234') and ID2 in (select ID2 from Table3 where column2='5678')

0
投票

我想,那个问题

select reject_ID from error_table where SOEID='A'

返回没有行,而这一行

select reject_ID from error_table

返回(或至少第一次返回小于第二次)。因此,您的第一个查询不返回任何行,因为它们都被条件and reject_id not in (<a lot if IDs>)排除。第二个查询过滤条件为and reject_id not in (<no rows>)的行 - 因此不排除任何行。

© www.soinside.com 2019 - 2024. All rights reserved.