为什么要选择'2019-05-03':: timestamp-'2018-05-07':: timestamp <'1 year 1 day':: INTERVAL; 在PostgreSQL中返回FALSE?

ket*_*nsk 5 postgresql

我正在尝试比较两个日期,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

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

lab*_*chn 7

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

注意:

select timestamp '2019-05-03' - timestamp '2018-05-07' < interval '366 day';
Run Code Online (Sandbox Code Playgroud)

给您预期的结果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.
 */
Run Code Online (Sandbox Code Playgroud)

因此,您的查询询问:

select 361 * 24 * 3600 * 1000000 < (1 * 12 * 30 * 24 * 3600 * 1000000) + (1 * 24 * 3600 * 1000000);
Run Code Online (Sandbox Code Playgroud)

要么,

select 31,190,400,000,000 < 31,190,400,000,000;
Run Code Online (Sandbox Code Playgroud)

这显然是错误的。^^