无法按别名过滤
Can't filter by alias
created_at - 使用 timzone
键入时间戳
查询:
select id,
created_at,
extract(epoch from CURRENT_TIMESTAMP - created_at) as delta_sec
from shop_order
成功的工作。不错
现在我只想显示 delta_sec > 10000
的记录
我试试这个:
select id,
created_at,
extract(epoch from CURRENT_TIMESTAMP - created_at) as delta_sec
from shop_order
where delta_sec > 10000
但是我得到错误:
ERROR: column "delta_sec" does not exist
LINE 5: where delta_sec > 10000
^
SQL state: 42703
Character: 125
只需重复表达式而不是使用其别名,例如:
select
id,
created_at,
extract(epoch from CURRENT_TIMESTAMP - created_at)
from shop_order
where extract(epoch from CURRENT_TIMESTAMP - created_at) > 10000
如果您担心数据库将 运行 表达式两次并因此减慢您的查询速度:请放心,让 PostgreSQL 来处理它。
或者,如果要使用别名进行过滤,则先将数据放入 CTE 中:
WITH cte_name AS (
SELECT
id,
created_at,
extract(epoch from CURRENT_TIMESTAMP - created_at) as delta_sec
FROM shop_order
)
SELECT *
FROM cte_name
WHERE delta_sec > 10000
created_at - 使用 timzone
键入时间戳查询:
select id,
created_at,
extract(epoch from CURRENT_TIMESTAMP - created_at) as delta_sec
from shop_order
成功的工作。不错
现在我只想显示 delta_sec > 10000
的记录我试试这个:
select id,
created_at,
extract(epoch from CURRENT_TIMESTAMP - created_at) as delta_sec
from shop_order
where delta_sec > 10000
但是我得到错误:
ERROR: column "delta_sec" does not exist
LINE 5: where delta_sec > 10000
^
SQL state: 42703
Character: 125
只需重复表达式而不是使用其别名,例如:
select
id,
created_at,
extract(epoch from CURRENT_TIMESTAMP - created_at)
from shop_order
where extract(epoch from CURRENT_TIMESTAMP - created_at) > 10000
如果您担心数据库将 运行 表达式两次并因此减慢您的查询速度:请放心,让 PostgreSQL 来处理它。
或者,如果要使用别名进行过滤,则先将数据放入 CTE 中:
WITH cte_name AS (
SELECT
id,
created_at,
extract(epoch from CURRENT_TIMESTAMP - created_at) as delta_sec
FROM shop_order
)
SELECT *
FROM cte_name
WHERE delta_sec > 10000