myisam表,单列索引,最大长度不能超过 1000 bytes; innodb表,单列索引,最大长度不能超过 767 bytes;
utf8 编码时 一个字符占三个字节 varchar 型能建立索引的最大长度分别为 myisam 1000/3 333 innodb 767/3 255
1、先检查一下数据库被限制了索引的大小 SHOW variables like ‘innodb_large_prefix’; 如果查询的值是off的话,执行下面的命令 SET GLOBAL INNODB_LARGE_PREFIX = ON; 2、执行完了,还需要查看当前innodb_file_format引擎格式类型是不是BARRACUDA SHOW variables like ‘innodb_file_format’; 如果不是的话则需要修改 SET GLOBAL innodb_file_format = BARRACUDA;
在my.cnf配置文件中同步更改
###########################################
innodb_large_prefix=on
##########################################
utf8mb4 编码时 一个字符占四个字节 varchar 型能建立索引的最大长度分别为 myisam 1000/4 250 innodb 767/4 191
CREATE TABLE `table_name` ( `id` int(11) NOT NULL AUTO_INCREMENT, `apple_id` varchar(255) DEFAULT 'unknown' COMMENT 'apple_id', `ipad_id` varchar(255) NOT NULL COMMENT 'ipad id', `version` varchar(255) DEFAULT 'unknown' COMMENT '版本信息', `start_time` datetime NOT NULL COMMENT '创建时间', `end_time` datetime NOT NULL COMMENT '结束时间', PRIMARY KEY (`id`), KEY `idx_ipad_id` (`ipad_id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT ='退出实例表' AUTO_INCREMENT = 1
###########
# 这里用了InnoDB和utf8mb4
如果是utf8mb4字符集,如果将innodb_large_prefix关闭,则767字节除以4(因为utf8mb4字符集中,一个字符最多可占用4字节),则最多只能容纳191个字符,因此也只能创建191个字符的索引
如果是utf8字符集,则可创建255个字符的索引,即767字节除以3(utf8字符集中,一个字符最多占用3字节),因此在定义varchar字段时,尽量小于256,避免创建前缀索引,因为前缀索引有使用限制,字符集为utf8,单列varchar(255)是可以创建索引的上限,256即报错。
# percona版本为5.7
# set global innodb_large_prefix=OFF;
(apple) > show create table user\G; *************************** 1. row *************************** Table: user Create Table: CREATE TABLE `user` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL DEFAULT '', `ids` varchar(32) NOT NULL DEFAULT '', `address` varchar(255) NOT NULL DEFAULT '', `inno` varchar(500) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `uk_ids` (`ids`), KEY `idx_name` (`name`(20)) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 1 row in set (0.00 sec) ERROR: No query specified Fri Sep 4 15:54:03 2020(apple) > alter table user add index idx_inno_address(inno(192)); ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes Fri Sep 4 15:54:26 2020(apple) > alter table user add index idx_inno_address(inno(191)); Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0 Fri Sep 4 15:54:30 2020(apple) >