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

标签 sql postgresql postgresql-9.3

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

伪代码:

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

有什么 SQL 技巧吗?

最佳答案

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

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

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

或者,您可以将上面的内容重写为公用表表达式:

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

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

上有索引时

关于sql - Postgres如何使用子句实现计算列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32187583/

相关文章:

postgresql - 我可以在 PostgreSQL 中获得 CSV header 但没有行数吗?

PostgreSQL 使用西里尔文排序 "ь"

mysql更新另一列为主键值

MySql 查询 - 基于条件需要 'ORDER BY' 选项

sql - sql中并行插入语句会导致死锁吗?

php - 如何使用SQl语法从MySQL表中的组中选择最新记录

postgresql - Plpgsql:如何在声明部分为变量赋值?

java - 如何通过 JDBC 使用包含问号 "?"的 PostgreSQL JSON(B) 运算符

PostgreSQL 9.3 : Function is not unique error

sql - 如何进行查询以返回 PostgreSQL 中两个表之间的差异