我想在from和where子句中使用相同的子查询。尝试了以下两种方法,但是在两种情况下在查询的不同位置都遇到相同的错误。
查询1:
select * from (subquery1) as t_feature where id = (select MAX(id) from t_feature);
查询2:
select * from t_feature where id = (select MAX(id) from (subquery1) as t_feature);
错误:
ERROR: relation "t_feature" does not exist
为了获得暂时的回报,我为子查询创建了一个视图,并用它代替了子查询。但是我不想为此案例创建视图。
with t_feature as (
...
)
select *
from t_feature
where id = (select MAX(id) from t_feature);
但是在Postgres中,有一种更好的方法可以使用distinct on()
来做到这一点
select distinct on (id) *
from the_table
order by id desc;