使用 mysql 日期计算时出现奇怪的结果

Strange result when calculating with mysql dates

这个计算 select cast('2016-06-01 00:00:00' as datetime)-cast('2016-05-31 00:00:00' as datetime) mySQL.

结果为 70 000 000

我知道我不应该使用该结构,但我很好奇 70000000 是什么?

首先,这不是减去日期或日期时间的方式。为此使用 datedifftimediff。只是说。所以见 MySQL Date and Time Functions.

但是看着

select cast('2016-06-01 00:00:00' as datetime)-cast('2016-05-31 00:00:00' as datetime);

70000000

select cast('2016-06-01 00:00:00' as datetime)-cast('2016-05-30 00:00:00' as datetime);

71000000

select cast('2016-06-01 00:00:00' as datetime)-cast('2016-06-02 00:00:00' as datetime);

-1000000

select cast('2016-06-01 00:00:00' as datetime)-cast('123' as char(3) );

20160600999877;

可以看到一种将它们视为 bigin 的模式。所以

select  20160601000000 - 20160531000000;

70000000

select  20160601000000 - 20160530000000;

71000000

所以这似乎是原因。

@Drew所示,执行减法时被视为BIGINT:

$ mysql --column-type-info

mysql> SELECT
    ->   `der`.`DATE_1`,
    ->   `der`.`DATE_2`,
    ->   `der`.`DATE_1` - `der`.`DATE_2` DIFF
    -> FROM (SELECT CAST('2016-06-01 00:00:00' AS DATETIME) `DATE_1`,
    ->              CAST('2016-05-31 00:00:00' AS DATETIME) `DATE_2`) `der`;
Field   1:  `DATE_1`
Catalog:    `def`
Database:   ``
Table:      `der`
Org_table:  ``
Type:       DATETIME
Collation:  binary (63)
Length:     19
Max_length: 19
Decimals:   0
Flags:      BINARY 

Field   2:  `DATE_2`
Catalog:    `def`
Database:   ``
Table:      `der`
Org_table:  ``
Type:       DATETIME
Collation:  binary (63)
Length:     19
Max_length: 19
Decimals:   0
Flags:      BINARY 

Field   3:  `DIFF`
Catalog:    `def`
Database:   ``
Table:      ``
Org_table:  ``
Type:       LONGLONG
Collation:  binary (63)
Length:     16
Max_length: 8
Decimals:   0
Flags:      BINARY NUM 

-- 20160601000000       20160531000000
+---------------------+---------------------+----------+
| DATE_1              | DATE_2              | DIFF     |
+---------------------+---------------------+----------+
| 2016-06-01 00:00:00 | 2016-05-31 00:00:00 | 70000000 |
+---------------------+---------------------+----------+
1 row in set (0,00 sec)