首页 > 解决方案 > 为什么 SELECT '2019-05-03'::timestamp - '2018-05-07'::timestamp < '1 year 1 day'::INTERVAL; 在 postgresql 中返回 FALSE?

问题描述

我正在尝试比较两个日期,TRUE如果第一个日期距离第二个日期小于“1 年 1 天”,则返回。

使用 361 天而不是 '1 year 1 day' 返回 FALSE,但这是有道理的,因为 justify_interval('360 days'::interval) 结果是 '1 year'

但是当我跑步时, SELECT '2019-05-03'::timestamp - '2018-05-07'::timestamp < '1 year 1 day'::INTERVAL; 我得到FALSE了,当我跑步时

SELECT '2019-05-03'::timestamp - '1 year 1 day'::INTERVAL < '2018-05-07'::timestamp; 我明白了TRUE

为什么这些返回不同的东西?

标签: postgresql

解决方案


我在文档中找不到它,但这是由于间隔表示和比较的方式。

注意:

select timestamp '2019-05-03' - timestamp '2018-05-07' < interval '366 day';

给你预期的结果TRUE

为了比较两个区间,Postgres 首先将区间转换为整数。这是以非常幼稚的方式完成的,涉及年份:

/*
 *      interval_relop  - is interval1 relop interval2
 *
 * Interval comparison is based on converting interval values to a linear
 * representation expressed in the units of the time field (microseconds,
 * in the case of integer timestamps) with days assumed to be always 24 hours
 * and months assumed to be always 30 days.  To avoid overflow, we need a
 * wider-than-int64 datatype for the linear representation, so use INT128.
 */

因此,您的查询是:

select 361 * 24 * 3600 * 1000000 < (1 * 12 * 30 * 24 * 3600 * 1000000) + (1 * 24 * 3600 * 1000000);

或者,

select 31,190,400,000,000 < 31,190,400,000,000;

这显然是错误的。^^


推荐阅读