MySQL-MySQL的utf8mb4编码

多年以前记得自己使用MySQL建表编码一般记为UTF-8,后来再捡起来数据库的知识,发现公司里的建表SQL(也包括CREATE DATABASE)这里的charset已经统一为了utf8mb4 ,遂将这部分知识重新整理记录如下

MySQL的UTF-8

我们最常使用的UTF-8是一种变长字符编码,对于unicode定义的字符的code point,UTF-8会使用1到4个字节对其进行表示。

在MySQL的UTF-8其实是其内部编码utf8mb3的别名,对于code point,最多使用3个字节进行表示,这样就势必会造成一部分字符的丢失。

到了5.5.3版本,utf8mb4弥补了不足:

The utf8mb4 character set has these characteristics:

  • Supports BMP and supplementary characters.

  • Requires a maximum of four bytes per multibyte character.

utf8mb4 contrasts with the utf8mb3 character set, which supports only BMP characters and uses a maximum of three bytes per character:

  • For a BMP character, utf8mb4 and utf8mb3 have identical storage characteristics: same code values, same encoding, same length.

  • For a supplementary character, utf8mb4 requires four bytes to store it, whereas utf8mb3 cannot store the character at all. When converting utf8mb3 columns to utf8mb4, you need not worry about converting supplementary characters because there are none.

在MySQL的官方文档下,utf8mb3后续是要明确移除的,包括了解到的很多企业,也是明确禁止使用该字符集。

从MySQL 8开始,其默认字符集编码变为了utf8mb4,此时建库表直接默认即可

编码转换

如果想要将已有的utf8mb3转为utf8mb4,可能会遇到如下的问题,Specified key was too long; max key length is 3072 bytes
在这里插入图片描述
首先,对于列内容没有影响,因为原本就最多只能使用3个字节进行编码表示,额外的字符集的内容根本存储不进去,现在转为utf8mb4,对原本内容根本不造成影响。

对表结构来说是有影响的,这点在MySQL的文档说的比较明确

In terms of table structure, these are the primary potential incompatibilities:

For the variable-length character data types (VARCHAR and the TEXT types), the maximum permitted length in characters is less for utf8mb4 columns than for utf8mb3 columns.

For all character data types (CHAR, VARCHAR, and the TEXT types), the maximum number of characters that can be indexed is less for utf8mb4 columns than for utf8mb3 columns.

Consequently, to convert tables from utf8mb3 to utf8mb4, it may be necessary to change some column or index definitions.

例如MySQL(InnoDB)对于索引的长度限制为767 bytes(在 COMPACT or REDUNDANT的行格式下),如果使用utf8mb3,那么可以存储字符数为255(通常以 3 字节 为最大值来计算),使用utf8mb4为191。那么当使用到了前缀索引,此时定义就会出问题了。

列也是同理。

MySQL官方文档的12.9.8 Converting Between 3-Byte and 4-Byte Unicode Character Sets 这一章节已经把问题解释的很清楚,可以查阅。

参考
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值