首页 > 解决方案 > 如何在 from 和 where 子句中使用相同的 psql 子查询?

问题描述

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

对于临时灵魂,我为子查询创建了一个视图,并用它来代替子查询。但我不想为这种情况创建视图。

标签: postgresqlsubquerycorrelated-subquery

解决方案


使用公用表表达式

with t_feature as (
   ...
) 
select * 
from t_feature 
where id = (select MAX(id) from t_feature);

推荐阅读