【问题标题】:Why does SELECT '2019-05-03'::timestamp - '2018-05-07'::timestamp < '1 year 1 day'::INTERVAL; return FALSE in postgresql?为什么 SELECT '2019-05-03'::timestamp - '2018-05-07'::timestamp < '1 year 1 day'::INTERVAL;在 postgresql 中返回 FALSE?
【发布时间】:2019-09-22 10:22:36
【问题描述】:

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

使用 361 天而不是“1 年 1 天”返回 FALSE,但基于 why justify_interval('360 days'::interval) results '1 year' 这是有意义的。

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

SELECT '2019-05-03'::timestamp - '1 year 1 day'::INTERVAL &lt; '2018-05-07'::timestamp; 我得到TRUE

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

【问题讨论】:

    标签: postgresql


    【解决方案1】:

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

    注意:

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

    给你TRUE的预期结果。

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

    /*
     *      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;
    

    这显然是错误的。 ^^

    【讨论】:

    • 这部分是什么意思:24 * 86400?不应该只是8640024 * 3600 吗? (虽然确实不会改变最终结果)
    • 是的,已在答案中修复。谢谢!
    猜你喜欢
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2019-05-02
    • 2013-02-25
    相关资源
    最近更新 更多