gpt4 book ai didi

比较日期列和日期时间/时间字符串时的Mysql隐式转换

转载 作者:行者123 更新时间:2023-11-29 05:58:01 25 4
gpt4 key购买 nike

我有一个包含 Date 列的表格。它有一行 my_date 列的值为 2017-11-24

SELECT * FROM mytable WHERE my_date = '2017-11-24 00:00:00' 返回该行。

虽然 SELECT * FROM mytable WHERE my_date = '2017-11-24 00:00:01' 没有。

来自 mysql 文档; this page

If one of the arguments is a TIMESTAMP or DATETIME column and the other argument is a constant, the constant is converted to a timestamp before the comparison is performed. This is done to be more ODBC-friendly. This is not done for the arguments to IN().

如果我对此的解释正确,在第二个查询中,右侧的常量将隐式转换为 Date 字段

second page对于类型转换说 -

Conversion to a DATE value takes fractional seconds into account and rounds the time part. For example, '1999-12-31 23:59:59.499' becomes '1999-12-31', whereas '1999-12-31 23:59:59.500' becomes '2000-01-01'.

示例显示 1999-12-31 23:59:59.499 -> 1999-12-31。我知道显式转换是首选,但我想知道为什么 mysql 选择对列值而不是常量进行类型转换,或者这里是否发生了其他事情。

最佳答案

我认为您没有正确解释文档。您引用的第一页是关于将 DATETIMETIMESTAMP 与常量进行比较。您正在将 DATE 与常量进行比较,因此 this logic应适用:

Conversion of DATE values:

Conversion to a DATETIME or TIMESTAMP value adds a time part of '00:00:00' because the DATE value contains no time information.

所以这就像比较 '2017-11-24 00:00:00' = '2017-11-24 00:00:01' 会明智地返回 false。

将 DATE 与 DATETIME/TIMESTAMP 进行比较类似于将 int 与 double 进行比较,因为隐式转换适用于不太精确的值。您不会期望 42 匹配 42.1,同样您也不应该期望 2017-11-24 匹配 2017-11 -24 00:00:01

关于比较日期列和日期时间/时间字符串时的Mysql隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47561524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com