4

我创建了一个带有 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)

这是为什么?

4

4 回答 4

7

好的,问题是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,因为字符串正好包含一个两字节字符!

于 2012-11-06T05:22:35.977 回答
2
       The following table illustrates the differences between CHAR and VARCHAR
 by showing the result of storing various string values into CHAR(4) and
 VARCHAR(4) columns (assuming that the column uses a single-byte character
 set such as latin1).

    Value   |CHAR(4)    |Storage Required   |VARCHAR(4) |Storage Required
===================================================================================
    ''          '    '  4 bytes            ''           1 byte
    'ab'        'ab  '  4 bytes            'ab'         3 bytes
    'abcd'      'abcd'  4 bytes            'abcd'       5 bytes
    'abcdefgh'  'abcd'  4 bytes            'abcd'       5 bytes
===================================================================================


       The values shown as stored in the last row of the table apply only when
  not using strict mode; if MySQL is running in strict mode, values that exceed 
  the column length are not stored, and an error results.
于 2012-11-06T04:51:14.373 回答
1

VARCHAR 的有效最大长度为 65,535 字节。您创建 VARCHAR 列时使用的数字 5,000 实际上并不限制 VARCHAR 列的允许存储长度。与 CHAR 数据类型相比,这是一种不同的行为。

11.4.1. CHAR 和 VARCHAR 类型

于 2012-11-06T04:48:59.220 回答
0

会不会是 5000 从零开始,然后指望给你 5001 个字符。它做 5002 吗?

于 2012-11-06T04:38:20.917 回答