偶遇ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes

今天在对一张表加索引时候出现如下报错:

mysql> ALTER TABLE ym_sys_dict ADD INDEX idx_dcode_dvalue (`dict_code`, `dict_value`);
ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes

查阅文档时候,看到如下解释:

"For CHAR, VARCHAR, BINARY, and VARBINARY columns, indexes can be created that use only the leading part of column values, using col_name(length) syntax to specify an index prefix length.  
...  
Prefixes can be up to 1000 bytes long (767 bytes for InnoDB tables). Note that prefix limits are measured in bytes, whereas the prefix length in CREATE TABLE statements is interpreted as number of characters ...">>>
对于myisam和innodb存储引擎,prefixes的长度限制分别为1000 bytes和767 bytes。注意prefix的单位是bytes,但是建表时我们指定的长度单位是字符。  
A utf8 character can use up to 3 bytes. Hence you cannot index columns or prefixes of columns longer than 333 (MyISAM) or 255 (InnoDB) utf8 characters.  >>以utf8字符集为例,一个字符占3个bytes。因此在utf8字符集下,对myisam和innodb存储引擎创建索引的单列长度不能超过333个字符和255个字符

mysql索引长度限制:

1)单列索引:

mysql 在创建单列索引的时候对列的长度是有限制的 myisam和innodb存储引擎下长度限制分别为1000 bytes和767 bytes。(注意bytes和character的区别)

2) 组合索引:

对于innodb存储引擎,多列索引的长度限制如下: 每个列的长度不能大于767 bytes;所有组成索引列的长度和不能大于3072 bytes

smallint 占2个bytes,timestamp占4个bytes,utf8字符集。utf8字符集下,一个character占三个byte。

对于这个问题,解决方法有两个:

1)修改参数 innodb_large_prefix,该参数默认为OFF,修改为ON

mysql> show variables like 'innodb_large_prefix';
+---------------------+-------+
| Variable_name       | Value |
+---------------------+-------+
| innodb_large_prefix | OFF   |
+---------------------+-------+

2)修改字段长度

查看表结构:

mysql> show create table ym_sys_dict \G
*************************** 1. row ***************************
       Table: ym_sys_dict
Create Table: CREATE TABLE `ym_sys_dict` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `dict_name` varchar(100) NOT NULL COMMENT '字典名称',
  `dict_type` varchar(100) NOT NULL COMMENT '字典类型',
  `dict_code` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `dict_value` varchar(1000) DEFAULT NULL,
  `order_num` int(11) DEFAULT '0' COMMENT '排序',
  `remark` varchar(255) DEFAULT ' ' COMMENT '备注',
  `del_flag` tinyint(4) DEFAULT '0' COMMENT '删除标记  -1:已删除  0:正常',
  PRIMARY KEY (`id`),
  UNIQUE KEY `dict_type` (`dict_type`,`dict_code`)
) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=utf8 COMMENT='数据字典表'

经和开发沟通,dict_value字段长度设置过长,改字段长度为100

alter table ym_sys_dict modify dict_value varchar(100);

然后可以正常添加索引

mysql> ALTER TABLE ym_sys_dict ADD INDEX idx_dcode_dvalue (`dict_code`, `dict_value`);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值