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

时间:2012-11-06 04:35:45

标签: mysql varchar

我创建了一个包含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 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分: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.

答案 2 :(得分:1)

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

11.4.1. The CHAR and VARCHAR Types

答案 3 :(得分:0)

是5000从0开始,然后依靠给你5001个字符。 它做5002吗?