MySQL CAST为DATE [英] MySQL CAST as DATE

查看:415
本文介绍了MySQL CAST为DATE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解什么向MySQL中的DATE类型转换一个值。以下是我尝试过的一些事情:

I'm trying to understand what casting a value to the DATE type in MySQL does. Here are some things I have tried:

SELECT CAST('3' AS DATE);
-- null

SELECT CAST(3 AS DATE);
-- null

SELECT CAST('2014-07-01 19:00:01' AS DATE);
-- 2014-07-01

SELECT DATE('2014-07-01 19:00:01');
-- 2014-07-01

SELECT CAST('2014-07-01' AS DATE);
-- 2014-07-01

SELECT DATE('2014-07-01');
-- 2014-07-01

SELECT CAST('2014-07-50' AS DATE);
-- null

SELECT DATE('2014-07-50');
-- null

SELECT DATE(''), CAST('' AS DATE), DATE(0), CAST(0 AS DATE);
-- null, null, 0000-00-00, 0000-00-00

我尝试过的一切似乎将它转换为 null ,如果它是无效的或返回字符串的日期部分,如果它是一个有效的日期。我甚至尝试使用斜杠和其他格式的日期,结果相同。

Everything I've tried seems to either convert it to null if it's invalid or return the date portion of the string if it's a valid date. I've even tried dates with slashes and other formats, same results.

使用 DATE(expr) 函数和CAST(expr AS DATE)


DATE(expr):提取日期的日期部分或日期时间表达式expr。

DATE(expr): Extracts the date part of the date or datetime expression expr.

CAST(expr AS类型) CAST() / code>函数使用任何类型的表达式,并生成指定类型的结果值,类似于 CONVERT()

同样的问题也可以在 TIME(expr) CAST (expr AS TIME)

Similarly, the same question can be asked about times with TIME(expr) and CAST(expr AS TIME).

推荐答案

检查MySQL 5.6的源代码 CAST() CONV ERT()调用相同的内部函数 Item_date_typecast DATE() code> Item_date_typecast

Checking the source code of MySQL 5.6 CAST() and CONVERT() calls to the same internal function Item_date_typecast, DATE() calls to Item_date_typecast too.

总之, 之间没有区别 DATE(expr)函数和 CAST(expr AS DATE)

In conclusion there is no difference between DATE(expr) function and the CAST(expr AS DATE).

参考:

https://github.com/mysql/mysql-server/blob/5.6/sql/sql_yacc.yy

https://github.com/mysql/mysql-server/blob/5.6/sql/item_create。 cc

这篇关于MySQL CAST为DATE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆