You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从SQL Server迁移至PostgreSQL:时间戳差值比较问题

PostgreSQL中时间戳差值超过90天的正确写法

你原来的PostgreSQL语句报错核心原因是类型不匹配:stored_timestamp - current_timestamp得到的是interval(时间间隔)类型,而右边的stored_timestamp + interval '90 Days'是timestamp(时间戳)类型,这俩类型没法直接用>比较,所以触发了operator does not exist: interval > timestamp错误。

针对你的需求,这里提供两种正确的写法,适配PostgreSQL语法:

写法1:直接比较时间间隔(和SQL Server逻辑最接近)

直接计算当前时间与存储时间的差值,判断是否大于90天的间隔:

(current_timestamp - stored_timestamp) > INTERVAL '90 days'

或者用PostgreSQL专门的AGE()函数计算时间差,再判断:

AGE(current_timestamp, stored_timestamp) > INTERVAL '90 days'

这两种写法都是用interval类型和interval类型比较,完全符合语法要求。

写法2:反向判断(性能更优,推荐)

换个逻辑,判断存储时间是否早于「当前时间减去90天」,这种写法如果stored_timestamp字段有索引,数据库可以直接利用索引查询,性能更好:

stored_timestamp < current_timestamp - INTERVAL '90 days'

补充说明

SQL Server的DATEDIFF(DAY, stored_timestamp, GETDATE())是计算两个时间之间的天数差,PostgreSQL里对应的逻辑用上面两种写法都能实现,其中写法2在大数据量场景下更高效。

内容的提问来源于stack exchange,提问作者Syv718

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:52:04