gpt4 book ai didi

mysql - 为什么 MySQL VARCHAR 允许超过最大长度?

转载 作者:可可西里 更新时间:2023-11-01 07:49:01 27 4
gpt4 key购买 nike

我用 UTF-8 VARCHAR(5000) 创建了一个表,并用数据填充了它。但看起来这个字段允许的数据比指示的要多:

mysql> DESCRIBE test;
+---------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| comment | varchar(5000) | YES | | NULL | |
+---------+------------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

mysql> SELECT MAX(LENGTH(comment)) FROM test;
+----------------------+
| MAX(LENGTH(comment)) |
+----------------------+
| 5001 |
+----------------------+
1 row in set (0.01 sec)

这是为什么?

最佳答案

好的,问题是LENGTH()返回以字节 为单位的长度,而不是字符。因为字符串是 UTF-8,所以我需要使用 CHAR_LENGTH()相反:

mysql> DESCRIBE test;
+---------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| comment | varchar(5000) | YES | | NULL | |
+---------+------------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

mysql> SELECT MAX(LENGTH(comment)) FROM test;
+----------------------+
| MAX(LENGTH(comment)) |
+----------------------+
| 5001 |
+----------------------+
1 row in set (0.01 sec)

mysql> SELECT MAX(CHAR_LENGTH(comment)) FROM test;
+----------------------+
| MAX(LENGTH(comment)) |
+----------------------+
| 5000 |
+----------------------+
1 row in set (0.01 sec)

长度为 5001,因为该字符串恰好包含一个两字节字符!

关于mysql - 为什么 MySQL VARCHAR 允许超过最大长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244462/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com