这是一件使我困惑的奇怪事情。它与业务逻辑无关,而与SQL语法有关,或者至少我想是这样。

我创建了一个表,并用如下数据填充它:

create table test (
   col1 int,
   col2 int
);

insert into test values
(1, 1),
(2, 2),
(3, 3);


当我执行查询时

select *
from test t1
where exists(
    select 1
    from test t2
    join test t3
    on t2.col1 = t3.col1
    where t2.col2 = t1.col2
);


它产生以下结果(SQL fiddle):

| col1 | col2 |
|------|------|
|    1 |    1 |
|    2 |    2 |
|    3 |    3 |


这是绝对正确的。

然后,我在子查询中将where更改为and

select *
from test t1
where exists(
    select 1
    from test t2
    join test t3
    on t2.col1 = t3.col1
    and t2.col2 = t1.col2
);


这将产生以下错误(SQL fiddle):


  “ on子句”中的未知列“ t1.col2”


我已经搜索了很长一段时间的原因,无法找出原因。

我希望有人能让我摆脱这种困惑。任何帮助表示赞赏。

最佳答案

这不是语法错误。别名t1存在于“外部查询”中。只有WHERE子句或HAVING子句允许您引用外部查询(并且在执行此操作时会形成“相关”子查询)。

JOIN无法引用外部查询(即,联接只能引用表别名t2和t3,因为它只能引用“内部”查询中的别名)

-- the "Outer query" is:
select *
from test t1

-- the "inner query" is:
select 1
from test t2
join test t3
on t2.col1 = t3.col1


通过引用别名t1在where子句中引入“相关”

选择 *
从测试T1
哪里存在(
    选择1
    从测试t2
    加入测试T3
    在t2.col1 = t3.col1上
    其中t2.col2 = T1.col2
);

10-07 19:12
查看更多