如何在from和where子句中使用相同的psql子查询?

问题描述 投票:0回答:1

我想在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

为了获得暂时的回报,我为子查询创建了一个视图,并用它代替了子查询。但是我不想为此案例创建视图。

postgresql subquery correlated-subquery
1个回答
0
投票

使用common table expression

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;
© www.soinside.com 2019 - 2024. All rights reserved.