类型 | 备注 |
---|---|
DATE | YYYY-MM-DD |
DATETIME | YYYY-MM-DD HH:mm:ss |
TIME | HH:mm:ss |
DECIMAL | 通常用于带小数位 |
CHAR | 固定长度字符串 |
NCHAR | 类型于CHAR一致 |
SIGNED | 一个有符号的64整数位 |
UNSIGNED | 一个无符号的64整数位 |
BINARY | 二进制字符串 |
JSON | MySQL 5.7.8 及更高版本 |
注意:
其中DATE支持的范围是: 1000-01-01 至 9999-12-31,(实验版本为:)
如果为: 999-01-01 结果则会0999-01-01。
如果为: 01-01-01则会为:2001-01-01。
mysql> select cast('999-11-11' as DATE); +---------------------------+ | cast('999-11-11' as DATE) | +---------------------------+ | 0999-11-11 | +---------------------------+ 1 row in set (0.00 sec)
mysql> select cast('01-11-11' as DATE); +--------------------------+ | cast('01-11-11' as DATE) | +--------------------------+ | 2001-11-11 | +--------------------------+ 1 row in set (0.00 sec)
mysql> select version(); +-----------+ | version() | +-----------+ | 5.7.20 | +-----------+ 1 row in set (0.00 sec)
2. CAST函数中expr的值可以转换为type,其转换的结果才正确,否则转换后的结果默认值,如Null,0等。
例如:一个Char类型转换为Demical类型,转换的结果就为0。
mysql> SELECT CAST('ANDYQIAN' AS DECIMAL); +-----------------------------+ | CAST('ANDYQIAN' AS DECIMAL) | +-----------------------------+ | 0 | +-----------------------------+ 1 row in set, 1 warning (0.00 sec)
转换案例
这里给出一些常用的类型转换例子。
DATE 类型
mysql> select cast('2017-12-14' as DATE); +----------------------------+ | cast('2017-12-14' as DATE) | +----------------------------+ | 2017-12-14 | +----------------------------+ 1 row in set (0.00 sec)
TIME 类型
mysql> select cast('12:00:00' as TIME); +--------------------------+ | cast('12:00:00' as TIME) | +--------------------------+ | 12:00:00 | +--------------------------+ 1 row in set (0.00 sec)
DATETIM 类型
mysql> select cast('2017-12-14 00:11:11' as DATETIME); +-----------------------------------------+ | cast('2017-12-14 00:11:11' as DATETIME) | +-----------------------------------------+ | 2017-12-14 00:11:11 | +-----------------------------------------+ 1 row in set (0.00 sec)
SIGNED类型
mysql> select cast('-1024' as SIGNED); +-------------------------+ | cast('-1024' as SIGNED) | +-------------------------+ | -1024 | +-------------------------+ 1 row in set (0.00 sec)
UNSIGNED类型
mysql> select cast('-1024' as UNSIGNED); +---------------------------+ | cast('-1024' as UNSIGNED) | +---------------------------+ | 18446744073709550592 | +---------------------------+ 1 row in set, 1 warning (0.00 sec)
DECIMAL类型
mysql> select cast('18.11' as DECIMAL(18,2)); +--------------------------------+ | cast('18.11' as DECIMAL(18,2)) | +--------------------------------+ | 18.11 | +--------------------------------+ 1 row in set (0.00 sec)
以上就是本次整理的全部内容,大家测试的时候可以输入命令尝试下,如果还有任何不明白的地方,大家可以在下方的留言区域讨论。