查询(子查询)的此部分无法引用该条目

nto*_*ier 3 sql postgresql

我在查询中遇到以下错误:

here is an entry for table "table1", but it cannot be referenced from this part of the query.
Run Code Online (Sandbox Code Playgroud)

这是我的查询:

SELECT id 
FROM property_import_image_results table1
  LEFT JOIN (
    SELECT created_at 
    FROM property_import_image_results
    WHERE external_url = table1.external_url
    ORDER BY created_at DESC NULLS LAST 
    LIMIT 1
  ) as table2 ON (pimr.created_at = table2.created_at)
WHERE table2.created_at is NULL
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 5

您需要横向联接才能在联接的子选择中引用外部表。

您还在pimr连接条件中引用别名,该别名在查询中的任何位置都不可用。因此,您需要将其更改table1为加入条件。

您还应该为内部查询中的表赋予别名以避免混淆:

SELECT id 
FROM property_import_image_results table1
  LEFT JOIN LATERAL (
    SELECT p2.created_at 
    FROM property_import_image_results p2
    WHERE p2.external_url = table1.external_url
    ORDER BY p2.created_at DESC NULLS LAST 
    LIMIT 1
  ) as table2 ON (table1.created_at = table2.created_at)
WHERE table2.created_at is NULL

编辑

也可以使用窗口函数解决这种查询:

select id
from (
  select id,  
         max(created_at) over (partition by external_url) as max_created
  FROM property_import_image_results
) t
where created_at <> max_created;
Run Code Online (Sandbox Code Playgroud)

可能比聚合和加入要快。但这很难说。横向连接也非常有效。它的优点是您可以将任何所需的列添加到结果中,因为不需要分组。