我正在尝试从时间戳字段中获取日期部分。我使用了这个SQL查询:
select timestamp, CAST(timestamp as date) as date from messages我得到了以下结果:
--------------------------------------------
| timestamp | date |
--------------------------------------------
| 2016-05-15 10:22:54 | 2016-05-16 |
--------------------------------------------如上所述,生成的日期字段返回错误的日期2016-05-16,而原始日期是2016-05-15。
我们如何解决这个问题呢?
发布于 2016-05-16 10:08:58
使用日期不强制转换,因为不是强制转换而是格式。
select timestamp, date(timestamp) as my_date from messages发布于 2016-05-16 10:31:08
那不是问题!它只设置了错误的time_zone。见样品
get time_zone
SHOW GLOBAL VARIABLES LIKE 'time_zone'; -- systemwide setting
SHOW VARIABLES LIKE 'time_zone'; -- session setting样本
MariaDB [mysql]> select t, CAST(t as date) FROM groupme LIMIT 1;
+---------------------+-----------------+
| t | CAST(t as date) |
+---------------------+-----------------+
| 2016-05-15 20:22:54 | 2016-05-15 |
+---------------------+-----------------+
1 row in set (0.00 sec)
MariaDB [mysql]> SET time_zone ='-12:00';
Query OK, 0 rows affected (0.00 sec)
MariaDB [mysql]> select t, CAST(t as date) FROM groupme LIMIT 1;
+---------------------+-----------------+
| t | CAST(t as date) |
+---------------------+-----------------+
| 2016-05-14 20:22:54 | 2016-05-14 |
+---------------------+-----------------+
1 row in set (0.00 sec)
MariaDB [mysql]>发布于 2016-05-16 10:14:45
我建议您使用DATE_FORMAT函数,而不是强制转换,因为您正在格式化日期,如
SELECT `timestamp`, DATE_FORMAT(`timestamp`, '%Y-%m-%d) as my_date from messages还请注意,CAST函数和DATE函数内部都调用Item_date_typecast函数,因此它们之间没有这种区别。
https://stackoverflow.com/questions/37251313
复制相似问题