MySQL中char类型和varchar类型的使用及他们之间的简单区别

发布时间 2023-09-06 02:08:57作者: wbnyua

官方文档

# 工具说明:使用的数据库可视化软件是 jetbrains datagrip
# mysql版本:8.0
# 数据库编码:utf8mb4
char和varchar的简单区别 官方文档原图:

image

浏览器翻译后:

image


# varchar = 前缀 + 数据。
# varchar类型需要使用一个定的长度空间来记录数据占用的字节数,也就是前缀。
# varchar最大占用65535字节。

create table hello(
    name varchar(65535)
);
# 上面的sql语句会直接报错:[42000][1074] Column length too big for column 'name' (max = 16383); use BLOB or TEXT instea
# utf8mb4使用4字节来存储一个字符,65535 * 4 已经超出了65535字节,也就是说只能存 65535 / 4 个字符
# varchar类型需要3字节来记录数据的占用的字节数:前缀3字节 + 16383个字符。
# 前缀具体占用多少字节,我还需要查阅资料,网上说占用两字节,但我写sql,会直接报错。
# 可以参考官方文档:https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html
# 我觉得是占用3字节的理由:
create table hello(
#   占用1字节
    nd tinyint,
#   16383 * 4 = 65532
#   65532 + 2 = 65534
    name varchar(16383)
);# 这个sql直接报错:[42000][1118] Row size too large.



create table hello(
#   占用4字节
    id int,
#     占用65535字节
    name varchar(16383)
);
# 上面的sql语句会直接报错:[42000][1118] Row size too large.
# The maximum row size for the used table type, not counting BLOBs, is 65535.
# This includes storage overhead, check the manual.
# You have to change some columns to TEXT or BLOBs

# 官网对行长度的解释:https://dev.mysql.com/doc/refman/8.0/en/column-count-limit.html
# 一行的长度最大为65535字节,无论多行列,加起来占用的字节数不能超过65535,当然,MySQL对列的长度也有限制。

# 如果想不报错:加起来刚好65535字节
create table hello(
#   占用4字节
    id int,
#     占用65531字节
    name varchar(16382)
);

后续还会补充

-----------页脚----------------