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

PostgreSQL报错CASE types interval and time with time zone cannot be matched如何解决

报错原因

CASE语句要求所有分支的返回值类型必须统一,你的代码中两个有效返回分支类型不兼容,因此触发报错:

  • 第一个分支date_end - date_start:两个timestamp类型计算差值,返回时间间隔(interval)类型
  • 第二个分支直接返回current_time:返回带时区的时间(time with time zone)类型

修复方案

从业务需求来看,你要的diff是时间差值,因此第二个分支不应该直接返回当前时间点,而是计算从date_start到当前时间的时间间隔,统一返回interval类型即可,修正后的SQL如下:

select
       case 
           when date_end is not null
              then date_end - date_start
           when date_start is not null
              then current_timestamp - date_start
           else null
       end as diff,
       column2
       /*, 其他字段 */
from t1

如果确实有特殊需求要保留原有返回逻辑(会导致diff字段含义混乱,不推荐),可以统一将返回值转为字符串类型:

select
       case 
           when date_end is not null
              then (date_end - date_start)::varchar
           when date_start is not null
              then current_time::varchar
           else null
       end as diff,
       column2
from t1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:15:01