介绍
cast 函数用于转换变量类型。官方文档: https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html 。
as 后面的参数支持 char
、signed
、unsigned
date
、datetime
、time
、decimal
等。
支持转换字符集。
convert 函数 (MySQL:convert 函数)与 cast 功能类似。
示例
mysql> select cast(1123 as char)
+--------------------+
| cast(1123 as char) |
+--------------------+
| 1123 |
+--------------------+
mysql> select cast("1123" as decimal)
+-------------------------+
| cast("1123" as decimal) |
+-------------------------+
| 1123 |
+-------------------------+
mysql> select cast("1123" as decimal(10,2))
+-------------------------------+
| cast("1123" as decimal(10,2)) |
+-------------------------------+
| 1123.00 |
+-------------------------------+
mysql> select cast('123' as signed)
+-----------------------+
| cast('123' as signed) |
+-----------------------+
| 123 |
+-----------------------+
mysql> select cast('-123' as unsigned)
+--------------------------+
| cast('-123' as unsigned) |
+--------------------------+
| 18446744073709551493 |
+--------------------------+
mysql> select cast('-123.45' as signed)
+---------------------------+
| cast('-123.45' as signed) |
+---------------------------+
| -123 |
+---------------------------+