MySQL:唯一索引的单列长度限制


#MySQL 笔记


MySQL:InnoDB存储引擎的限制 中提到对于使用utf8mb4字符集的表,TEXT、VARCHAR、CHAR等类型的列,只能用前面的 191 个字符做索引,因为 191×4=764,192×4=768,191个字符正好没有超过 767 字节的限制。如果 char、varchar 等定义的长度超过了 191,而指定索引时未说明索引长度,则会自动使用前191个字符做索引。

示例:

创建表:

create table test_table (
    c1 varchar(200) not null,
    INDEX idx_c1(c1)
) engine = InnoDB character set = utf8mb4;

查看创建表语句:

mysql> show create table test_table
+------------+-----------------------------------------+
| Table      | Create Table                            |
+------------+-----------------------------------------+
| test_table | CREATE TABLE `test_table` (             |
|            |   `c1` varchar(200) NOT NULL,           |
|            |   KEY `idx_c1` (`c1`(191))              |
|            | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
+------------+-----------------------------------------+

可以看到索引中 c1 自动取了前191个字符。

但是,若是唯一索引,单列的长度不能超过 191个字符,否则报错。

create table test_table (
    c1 varchar(200) not null,
    UNIQUE INDEX idx_c1(c1)
) engine = InnoDB character set = utf8mb4;

上面的建表语句会报错如下:

(1071, u'Specified key was too long; max key length is 767 bytes')

为什么唯一索引不自动取前191个字符呢?因为若这样做,唯一性就无法保证了。



( 本文完 )