我的查询出现以下错误:
here is an entry for table "table1", but it cannot be referenced from this part of the query.
这是我的疑问:
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
答案 0 :(得分:3)
您需要横向连接才能在连接的子选择中引用外部表。
您还在连接条件中引用别名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;
此可能比聚合和加入更快。但这很难说。横向连接也非常有效。它的优点是您可以将任何列添加到结果中,因为不需要分组。