MySQL CAST 作为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26165882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:05:44  来源:igfitidea点击:

MySQL CAST as DATE

mysqlsqldatecasting

提问by rink.attendant.6

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

我试图了解在 MySQL 中将值转换为 DATE 类型的作用。以下是我尝试过的一些事情:

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

Everything I've tried seems to either convert it to nullif 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.

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

What's the difference between using the DATE(expr)function and the CAST(expr AS DATE)?

使用DATE(expr)函数和使用函数有什么区别CAST(expr AS DATE)

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

CAST(expr AS type): The CAST()function takes an expression of any type and produces a result value of a specified type, similar to CONVERT()

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

CAST(expr AS type):CAST()函数接受任意类型的表达式并产生指定类型的结果值,类似于CONVERT()

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

同样,同样的问题可以用TIME(expr)和询问时间CAST(expr AS TIME)

回答by Ivan Cachicatari

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_typecasttoo.

检查MySQL 5.6的源代码CAST()CONVERT()调用相同的内部函数 Item_date_typecast,也DATE()调用 Item_date_typecast了。

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

总之是没有区别的之间DATE(expr)的功能和CAST(expr AS DATE)

Refs:

参考:

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

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

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