添加删除索引
# 添加索引 ALTER TABLE user ADD UNIQUE (name) # 删除索引 ALTER TABLE user DROP INDEX (name)
添加索引是遇到问题
MySQL添加索引Specified key was too long; max key length is 767 bytes
要设置为索引的字段太长,超过了767字节
name varchar(255) utf8mb4 # 255 * 4 = 1020 个字节 select version() # 5.6.45-log
处理方式
# 查看数据库被限制了索引的大小 SHOW variables like 'innodb_large_prefix' # 解除限制 SET GLOBAL INNODB_LARGE_PREFIX = ON; # 查看当前的innodb_file_format引擎格式类型 SHOW variables like 'innodb_file_format' # 修改 SET GLOBAL innodb_file_format = BARRACUDA;
创建表的时候指定表的 row format 格式为 Dynamic 或者 Compressed
如下示例:
create table user ( id int auto_increment primary key, name varchar(255) ) ROW_FORMAT=DYNAMIC default charset utf8mb4;
再次添加唯一索引就可以添加上了
参考
MySQL 建索引时 Specified key was too long; max key length is 767 bytes 错误的处理