Postgres如何使用子句实现计算列

Postgres how to implement calculated column with clause

我需要在 postgres 中按计算列进行过滤。使用 MySQL 很容易,但是如何使用 Postgres SQL 来实现?

伪代码:

select id, (cos(id) + cos(id)) as op from myTable WHERE op > 1;

有什么SQL技巧吗?

select id, (cos(id) + cos(id)) as op 
from selfies 
WHERE (cos(id) + cos(id)) > 1

您应该在 where 子句中指定计算,因为您不能使用 alias

如果不想重复表达,可以使用派生的table:

select *
from (
   select id, cos(id) + cos(id) as op 
   from myTable 
) as t 
WHERE op > 1;

这不会对性能有任何影响,只是SQL标准要求的语法糖。

或者,您可以将上面的内容重写为常见的 table 表达式:

with t as (
  select id, cos(id) + cos(id) as op 
  from myTable 
)
select *
from t 
where op > 1;

您更喜欢哪一种很大程度上取决于品味。 CTE 的优化方式与派生 table 相同,因此第一个可能更快,尤其是在表达式 cos(id) + cos(id)

上有索引的情况下