在 postgres 查询中对 table "t1" 的 FROM 子句条目的引用无效

Invalid reference to FROM-clause entry for table "t1" in postgres query

我正在尝试执行这样的查询...

select * from table1 as t1
left join (
    select * from table2 as t2
    where t2.id = t1.t2_id
) as tt2
where tt2.value = 'SOME VALUE'

& 我收到这样的错误...

ERROR: invalid reference to FROM-clause entry for table "t1"
  Hint: There is an entry for table "t1", but it cannot be referenced from this part of the query.

该错误消息完全有道理,但我只想知道是否可以将 't1' 的值与 't2' 的值相匹配,保持相同的结构?

如果你真的想要一个相关的子查询,你可以使用横向连接:

select *
from table1 t1 left join lateral
     (select * 
      from table2 t2
      where t2.id = t1.t2_id
     ) tt2
     on 1=1
where tt2.value = 'SOME VALUE';

请注意,where 子句会撤消左连接。我怀疑你真的想要一个简单的 left join:

select *
from table1 t1 left join
     table2 t2
     on t2.id = t1.t2_id and t2.value = 'SOME VALUE';

t1 中的 returns 行在 t2 中没有与 'SOME VALUE' 匹配的行。如果您不想要它们,请将 left join 更改为 inner join