postgresql - 为什么 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
。
为什么这些返回不同的东西?
解决方案
我在文档中找不到它,但这是由于间隔表示和比较的方式。
注意:
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;
这显然是错误的。^^
推荐阅读
- java - 想要将多个 JSON 对象存储到 jsonArray 并将结果作为单个字符串获取
- c# - 如何根据字符串动态调用类?
- android - 存储库模式未正确返回 LiveData
- javascript - 如何使用 gupsup ide 从 urlbar 获取主机名?
- microservices - 微服务的数据库设计
- ios - 如何使用 Xamarin 表单在 iOS 中设置 GPS 位置确认弹出窗口的间隔时间
- amazon-web-services - Terraform 0.12 aws_lambda_permission 资源每次应用都被替换
- java - org.openqa.selenium.WebDriverException: disconnected: received Inspector.detached event error during test execution using Selenium and Chromedriver
- flutter - 目标 kernel_snapshot 失败:异常:快照创建期间出错:空构建失败
- android - Play Install Referrer Library 添加 WRITE_EXTERNAL_STORAGE 和 READ_EXTERNAL_STORAGE 权限