参考 SQL 中的计算值

Referencing calculated value in SQL

我想知道为什么这不起作用(在 PostgreSQL 中):

create table t(c integer);
insert into t values(1);
insert into t values(2);
insert into t values(3);

select c+10 as result from t group by result order by result;
--> OK
select c+10 as result from t where result > 10;
--> ERROR:  column "result" does not exist

所以我可以在 group by 和 order by 中引用列结果,但不能在 where 中引用。这是为什么?

这只是一个简化的例子。在真实的事物中,select 部分有一个函数。我需要在 where-part 中那个函数的结果。我不想计算函数两次。执行此操作的最佳方法是什么(对于上面的示例,如何避免计算 c+10 两次)?

您不能在定义列的级别引用列别名。您需要将其包装在派生的 table:

select *
from (
    select c+10 as result 
    from t 
) x 
where result > 10;

这对性能没有影响,它只是语法糖

您可以使用 LATERAL:

SELECT result 
FROM t
,LATERAL (SELECT c+10) AS s(result)  -- here you calculate what you need
WHERE result > 10;

那你可以参考SELECT/WHERE/ORDER BY...条中的计算值。

SqlFiddleDemo


简化的执行顺序:

图片来自:http://social.technet.microsoft.com/wiki/contents/articles/20724.all-at-once-operations-in-t-sql.aspx

如您所见,WHERESELECT 之前,这就是为什么您不能在 WHERE.

中引用计算表达式的原因