【问题标题】:Wrong SELECT subquery in 'IN' condition'IN' 条件下的错误 SELECT 子查询
【发布时间】:2016-12-22 08:05:40
【问题描述】:

我做了这样的查询

SELECT *
FROM   TABLE_A
WHERE  1=1
   AND ID_NO IN (
         SELECT ID_NO
         FROM   TABLE_B
         WHERE  SEQ = '1'
   )

问题是 TABLE_B 中没有“ID_NO”列。所以我期待该查询不起作用。 但是这个查询有效。我不明白为什么。


为什么它没有导致错误?

【问题讨论】:

  • 请提供表结构
  • 这是一个正确的查询,如果 table_A 中的 ID_NO 与 table_B 中的 ID_NO 类型不同,则会导致问题,其他方式提供更多详细信息。

标签: sql oracle in-subquery


【解决方案1】:

如果 table_B 没有名为 ID_NO 的列,但 table_A 有,则查询是正确的。然后你会有一个相关的子查询,其中子查询 select ID_NO 引用 table_A 的外部 ID_NO 属性(可能没有意义,但对编译器是正确的)。

考虑以下架构:

create table table_a (
  id_no int
  );

create table table_b (
    other_id_no int
    );

insert into table_a values (1),(2);
insert into table_b values (1),(3);

然后,以下查询将编译;但它总是会产生一个空结果,因为它实际上意味着类似于 where id_no not in (id_no):

select * from  table_a where id_no not in (select id_no from table_b);

在处理子查询时,我建议使用表别名以避免这种意外行为。例如,下面的查询没有编译,编译器会提示你出了什么问题:

select * from  table_a a where a.id_no not in (select b.id_no from table_b b);
Error: Unknown column 'b.id_no' in 'field list'

纠正错误然后导致:

select * from  table_a a where a.id_no not in (select b.other_id_no from table_b b);

【讨论】:

  • 很好的答案。当我加入两个表(如“来自 TABLE_A,TABLE_B”)时,我总是使用别名来避免意外行为,但我从未在子查询上尝试过。那是我的错误。谢谢斯蒂芬的好评论
猜你喜欢
  • 1970-01-01
  • 2012-04-18
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 2011-05-09
  • 1970-01-01
相关资源
最近更新 更多