-2

我做了这样的查询

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

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


为什么它没有导致错误?

4

1 回答 1

5

如果 table_B 没有名为 ID_NO 的列,但 table_A 有,则查询是正确的。然后你会有一个相关的子查询,其中子查询选择 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);
于 2016-12-22T08:29:23.433 回答