在Mysql数据库平常运维过程当中,在表上建立索引是很常见的事情,但是一直没有思考过,单列索引到底能有多长呢。若是varchar类型的字段过长,建立单列索引会不会失败呢,下面就来一块儿探索一下吧。mysql
查阅官方文档,发如今MySQL5.6 版本后引入了参数 innodb_large_prefix,开启状况下,Innodb表的行记录格式是Dynamic或Compressed的前提下,能让单列索引的长度达到3072个字节长度,若是不开启这个参数,那么单列索引的长度就不能超过767个字节长度。sql
测试环境介绍
测试环境的是MySQL5.7版本,默认字符集是utf8。数据库
查看innodb_large_prefix参数运维
innodb_large_prefix参数在mysql5.7版本,默认是开启的。mysql> show variables like 'innodb_large%'; +---------------------+-------+ | Variable_name | Value | +---------------------+-------+ | innodb_large_prefix | ON | +---------------------+-------+ 1 row in set (0.02 sec)
查看测试表的默认记录格式
在mysql5.7版本中,Innodb表的行记录格式为Dynamic的。ide
mysql> show variables like 'innodb_default_row_format'; +---------------------------+---------+ | Variable_name | Value | +---------------------------+---------+ | innodb_default_row_format | dynamic | +---------------------------+---------+ 1 row in set (0.01 sec)
模拟测试
建立测试表和索引测试
mysql> create table t_test2 (id int not null,name varchar(1024) not null default '',primary key(id)); Query OK, 0 rows affected (0.02 sec) mysql> alter table t_test2 add index idx_t_test2_name(name); Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> create table t_test3 (id int not null,name varchar(1025) not null default '',primary key(id)); Query OK, 0 rows affected (0.03 sec) mysql> alter table t_test3 add index idx_t_test3_name(name); ERROR 1071 (42000): Specified key was too long; max key length is 3072
bytes从测试结果上能够看出,当varchar的字段长度超过1024以后,建立单列索引就会报错,为何呢,由于数据库的字符集是utf8,一个字符长度占用3个字节,那么单列索引的长度是3072,转换成字符 3072 / 3=1024,这样建表时,若是字段长度超过1024,建立索引就会失败。
关闭innodb_large_prefix参数测试code
关闭innodb_large_prefix参数orm
mysql> set global innodb_large_prefix=off; Query OK, 0 rows affected, 1 warning (0.11 sec) mysql> show variables like 'innodb_large_prefix'; +---------------------+-------+ | Variable_name | Value | +---------------------+-------+ | innodb_large_prefix | OFF | +---------------------+-------+ 1 row in set (0.00 sec) mysql> create table t_test4 (id int not null,name varchar(255) not null default '',primary key(id)); Query OK, 0 rows affected (0.02 sec) mysql> alter table t_test4 add index idx_t_test4_name(name); Query OK, 0 rows affected (0.35 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> create table t_test5 (id int not null,name varchar(256) not null default '',primary key(id)); Query OK, 0 rows affected (0.01 sec) mysql> alter table t_test5 add index idx_t_test5_name(name); ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes
能够看到此时,字段长度超过255,建立单列索引就会报错。索引
但是在生产,谁会在长度超过1024的列上建立索引呢,这不是有病么,因此建议将innodb_large_prefix参数关闭,避免在长字段上建立索引。ci