【问题标题】:Why the subtraction of two dates is different than the result from using DATEDIFF()?为什么两个日期相减与使用 DATEDIFF() 的结果不同?
【发布时间】:2023-02-25 08:53:52
【问题描述】:

这两个功能有何不同?两列都是日期类型。

我使用的查询是

SELECT 
     period_start,
     period_end,
     period_end - period_start AS subtract,
     DATEDIFF(period_start,period_end) AS datediff
FROM some table
period_start period_end substract datediff
2019-01-25 2019-02-28 103 34
2019-01-25 2019-02-28 103 34
2019-01-25 2019-02-28 103 34
2018-12-01 2020-01-01 18900 396

【问题讨论】:

  • 减法将其转换为 int 你的第一行是 228 -125,唯一正确的方法是使用日期函数

标签: mysql sql


【解决方案1】:

datediff()date_sub() 是执行日期比较的唯一有效方法。

减去两个日期是不确定的。它可能会将日期转换为数字并减去。

感谢@nbk,它在日期上执行了整数数学运算:

period_start period_end math result
2019-01-25 2019-02-28 190228-190125 103
2019-01-25 2019-02-28 190228-190125 103
2019-01-25 2019-02-28 190228-190125 103
2018-12-01 2020-01-01 200101-181201 18900

【讨论】:

  • 我不会说减法是未定义的,转换为数字是可靠的,只是没有用(除了总是产生正确的符号)
猜你喜欢
  • 1970-01-01
  • 2015-09-14
  • 2021-07-30
  • 2012-06-22
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
相关资源
最近更新 更多