【问题标题】:How to use same psql subquery in from and where clause?如何在 from 和 where 子句中使用相同的 psql 子查询?
【发布时间】:2020-03-17 09:17:03
【问题描述】:

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

使用common table expression

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

【讨论】:

  • 尝试使用公用表表达式,它有效。但不确定distinct 在这里如何提供帮助。 Distinct 消除了重复的行,但是我想选择具有最大值的行,并且可以有多个具有相同 MAX 值的行。
  • @S.K:那我误解了你的意图
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
相关资源
最近更新 更多