在previous post中,有人帮助我进行了子查询。现在,我想添加到查询中,但收到一条错误消息。 (我仍在学习有关子查询的规则。)
下面更新了SQL。错误是:
[Amazon](500310) Invalid operation: invalid reference to FROM-clause entry for table "application_stages";
SELECT t1.*, applications.status, applications.stage_name
FROM application_stages t1
JOIN (
select application_id, max(exited_on) as exited_on
from application_stages
group by application_id
) t2
USING (application_id,exited_on)
join applications on application_stages.application_id = applications.id
where application_id in ('91649746', '91991364', '96444221')
答案 0 :(得分:1)
为此使用窗口功能:
select ast.*, a.status, a.stage_name
from (select ast.*,
rank() over (partition by application_id order by exited_on desc) as seqnum
from application_stages ast
) ast join
applications a
on ast.application_id = a.id
where ast.seqnum = 1 and
ast.application_id in ('91649746', '91991364', '96444221');
您的查询有几个问题:
application_id
中的where
不明确application_stages
的别名为t1
,因此无法识别前者请注意,如果application_id
是一个数字(我猜是这种情况),则常量不应使用单引号。
答案 1 :(得分:1)
分配别名时,需要在所有子句中一致使用它们,并避免在其他表中使用相同名称的列引起歧义。考虑进行以下调整
SELECT s.*, a.status, a.stage_name
FROM application_stages s
JOIN (
select application_id, max(exited_on) as exited_on
from application_stages
group by application_id
) m
USING (application_id, exited_on)
JOIN applications a ON a.application_id = s.id
WHERE a.application_id IN ('91649746', '91991364', '96444221')