MySQL中CAST和CONVERT函数都用于数据范例转换

打印 上一主题 下一主题

主题 549|帖子 549|积分 1647

在 MySQL 中,CAST() 和 CONVERT() 函数都用于数据范例转换。虽然这两个函数在大多数情况下可以互换使用,但它们之间还是有一些细微的差异。
官方文档地点
https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html#function_cast
CAST() 函数

CAST() 函数是 SQL 标准中的数据范例转换函数。其基本语法如下:
  1. CAST(expression AS type)
  2. CAST(timestamp_value AT TIME ZONE timezone_specifier AS DATETIME[(precision)])
  3. timezone_specifier: [INTERVAL] '+00:00' | 'UTC'
复制代码


  • expression 是要转换的值或表达式。
  • type 是要转换为的数据范例。
例如,将整数转换为字符串:
  1. (root@localhost:mysql.sock)[(superdb)]>SELECT CAST(8860 AS CHAR) as v1;
  2. +------+
  3. | v1   |
  4. +------+
  5. | 8860 |
  6. +------+
  7. 1 row in set (0.00 sec)
复制代码
欺压转换函数对于在CREATE TABLE中创建具有特定范例的列很有用。。。SELECT语句
The cast functions are useful for creating a column with a specific type in a CREATE TABLE … SELECT statement
  1. (root@localhost:mysql.sock)[superdb]>CREATE TABLE t_new_table SELECT CAST('2024001' AS decimal(18,0)) as id,CAST('2000-01-01' AS DATE) AS col_1;
  2. Query OK, 1 row affected (0.01 sec)
  3. Records: 1  Duplicates: 0  Warnings: 0
  4. (root@localhost:mysql.sock)[superdb]>show create table t_new_table;
  5. +-------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  6. | Table       | Create Table                                                                                                                                                           |
  7. +-------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  8. | t_new_table | CREATE TABLE `t_new_table` (
  9.   `id` decimal(18,0) NOT NULL DEFAULT '0',
  10.   `col_1` date DEFAULT NULL
  11. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
  12. +-------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  13. 1 row in set (0.00 sec)
  14. (root@localhost:mysql.sock)[superdb]>desc t_new_table;
  15. +-------+---------------+------+-----+---------+-------+
  16. | Field | Type          | Null | Key | Default | Extra |
  17. +-------+---------------+------+-----+---------+-------+
  18. | id    | decimal(18,0) | NO   |     | 0       |       |
  19. | col_1 | date          | YES  |     | NULL    |       |
  20. +-------+---------------+------+-----+---------+-------+
  21. 2 rows in set (0.00 sec)
  22. (root@localhost:mysql.sock)[superdb]>select * from t_new_table;
  23. +---------+------------+
  24. | id      | col_1      |
  25. +---------+------------+
  26. | 2024001 | 2000-01-01 |
  27. +---------+------------+
  28. 1 row in set (0.00 sec)
复制代码
欺压转换为有符号或无符号的64位整数
use the SIGNED or UNSIGNED cast operator to cast a value to a signed or unsigned 64-bit integer
  1. (root@localhost:mysql.sock)[superdb]>SELECT 8-9 as v1,CAST(8 - 9 AS SIGNED) as v2, CAST(8 - 9 AS UNSIGNED) as v3;
  2. +----+----+----------------------+
  3. | v1 | v2 | v3                   |
  4. +----+----+----------------------+
  5. | -1 | -1 | 18446744073709551615 |
  6. +----+----+----------------------+
  7. 1 row in set (0.00 sec)
复制代码
从MySQL 8.0.22开始,CAST()支持使用AT TIMEZONE运算符检索以UTC为单位的TIMESTAMP值。唯一支持的时区是UTC;这可以指定为“+000:00”或“UTC”。此语法支持的唯一返回范例是DATETIME,其可选精度说明符范围为0到6(包括0到6)
Beginning with MySQL 8.0.22, CAST() supports retrieval of a TIMESTAMP value as being in UTC, using the AT TIMEZONE operator. The only supported time zone is UTC; this can be specified as either of '+00:00' or 'UTC'. The only return type supported by this syntax is DATETIME, with an optional precision specifier in the range of 0 to 6, inclusive.
TIMESTAMP values that use timezone offsets are also supported.
  1. (root@localhost:mysql.sock)[superdb]> SELECT @@system_time_zone;
  2. +--------------------+
  3. | @@system_time_zone |
  4. +--------------------+
  5. | CST                |
  6. +--------------------+
  7. 1 row in set (0.00 sec)
  8. (root@localhost:mysql.sock)[superdb]> CREATE TABLE t_cast_timezone (col_convert_datetime TIMESTAMP);
  9. Query OK, 0 rows affected (0.06 sec)
  10. (root@localhost:mysql.sock)[superdb]> INSERT INTO t_cast_timezone VALUES ROW(CURRENT_TIMESTAMP),ROW('2024-06-15 14:50:15');
  11. Query OK, 2 rows affected (0.00 sec)
  12. Records: 2  Duplicates: 0  Warnings: 0
  13. (root@192.168.80.85)[superdb]> TABLE t_cast_timezone;
  14. +----------------------+
  15. | col_convert_datetime |
  16. +----------------------+
  17. | 2024-06-15 22:06:07  |
  18. | 2024-06-15 14:50:15  |
  19. +----------------------+
  20. 2 rows in set (0.00 sec)
  21. (root@localhost:mysql.sock)[superdb]> SELECT CAST(col_convert_datetime AT TIME ZONE '+00:00' AS DATETIME) AS u FROM t_cast_timezone;
  22. +---------------------+
  23. | u                   |
  24. +---------------------+
  25. | 2024-06-15 14:06:07 |
  26. | 2024-06-15 06:50:15 |
  27. +---------------------+
  28. 2 rows in set (0.00 sec)
复制代码
CONVERT() 函数

CONVERT() 函数在某些数据库系统(如 MySQL)中提供,但在其他系统中大概不可用。其基本语法如下:
  1. CONVERT(expression, type)
复制代码
或(在某些数据库系统中)
  1. CONVERT(type, expression)
复制代码
但请注意,在 MySQL 中,CONVERT() 函数的语法与 CAST() 类似:
  1. CONVERT(expression, type)
复制代码


  • expression 是要转换的值或表达式。
  • type 是要转换为的数据范例。
例如,在 MySQL 中,将整数转换为字符串与 CAST() 函数的示例相同:
  1. (root@localhost:mysql.sock)[superdb]>SELECT CONVERT(123890,CHAR) as v1;
  2. +--------+
  3. | v1     |
  4. +--------+
  5. | 123890 |
  6. +--------+
  7. 1 row in set (0.01 sec)
复制代码
例如,在 MySQL 中,将整数转换为双精度decimal范例的示例
decimal 范例可以存储大量的数字,而且具有可配置的精度。例如,decimal(18,2) 可以存储最多 18 位数字,此中 2 位在小数点之后
  1. (root@localhost:mysql.sock)[superdb]>SELECT CONVERT(123890,decimal(18,2)) as v1;
  2. +-----------+
  3. | v1        |
  4. +-----------+
  5. | 123890.00 |
  6. +-----------+
  7. 1 row in set (0.00 sec)
  8. -- 将字符串转换为双精度decimal类型的示例
  9. (root@localhost:mysql.sock)[superdb]>SELECT CONVERT(123890,decimal(18,2)) as v1,CONVERT('123890',decimal(18,2)) as v2;
  10. +-----------+-----------+
  11. | v1        | v2        |
  12. +-----------+-----------+
  13. | 123890.00 | 123890.00 |
  14. +-----------+-----------+
  15. 1 row in set (0.00 sec)
复制代码
将日期字符串转换为日期范例
  1. (root@localhost:mysql.sock)[superdb]>SELECT CONVERT('2024-06-13', DATE) as v1,CONVERT('2024-06-13 13:16:24', DATETIME) as v2;
  2. +------------+---------------------+
  3. | v1         | v2                  |
  4. +------------+---------------------+
  5. | 2024-06-13 | 2024-06-13 13:16:24 |
  6. +------------+---------------------+
  7. 1 row in set (0.00 sec)
复制代码
字符集转换在二进制字符串的字母大小写转换之前也很有用。LOWER()和UPPER()在直接应用于二进制字符串时是无效的,由于lettercase的概念不适用。
Character set conversion is also useful preceding lettercase conversion of binary strings. LOWER() and UPPER() are ineffective when applied directly to binary strings because the concept of lettercase does not apply. To perform lettercase conversion of a binary string, first convert it to a nonbinary string using a character set appropriate for the data stored in the string
  1. (root@localhost:mysql.sock)[superdb]>SET @str = BINARY 'New York';
  2. Query OK, 0 rows affected, 1 warning (0.00 sec)
  3. (root@localhost:mysql.sock)[superdb]>SELECT LOWER(@str), LOWER(CONVERT(@str USING utf8mb4));
  4. +--------------------------+------------------------------------+
  5. | LOWER(@str)              | LOWER(CONVERT(@str USING utf8mb4)) |
  6. +--------------------------+------------------------------------+
  7. | 0x4E657720596F726B       | new york                           |
  8. +--------------------------+------------------------------------+
  9. 1 row in set (0.00 sec)
复制代码
使用 CONVERT() 举行字符集转换(注意:在某些数据库系统中,CONVERT() 大概不支持字符集转换,但MySQL的 CONVERT() 函数在 USING 子句的支持下可以这样做)
两者之间的差异


  • SQL 标准:CAST() 是 SQL 标准中的函数,而 CONVERT() 并非所有数据库系统都支持。
  • 语法:虽然在 MySQL 中 CONVERT() 的语法与 CAST() 类似,但在其他数据库中大概有所不同。
  • 功能:在某些数据库中,CONVERT() 大概提供额外的功能或选项,这些功能在 CAST() 中不可用。但在 MySQL 中,这两个函数在功能上非常相似。
  • 可读性:有时,CONVERT() 大概会被认为更具可读性,由于它更接近于许多编程语言中的范例转换语法。但是,由于 CAST() 是 SQL 标准中的函数,因此它通常更受推荐。
总结

在 MySQL 中,CAST() 和 CONVERT() 都可以用于数据范例转换,而且它们在功能上非常相似。然而,由于 CAST() 是 SQL 标准中的函数,因此通常更推荐使用它。但在其他数据库系统中,您大概需要检查这两个函数的可用性和功能差异。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

滴水恩情

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表