Navicat for Mysql中错误提示索引过长1071-max key length is 767 byte

1.建用户信息表 tb_person_info

create table tb_person_info(
    user_id int(10) auto_increment,
    `name` varchar(32) default null,
    gender varchar(2) default null,
    profile_img varchar(1024) default null,
    email varchar(1024) default null,
    enable_status int(2) not null default 0 comment '0:禁止访问商城,1:允许访问商城',
    user_type int(2) not null default 1 comment '1:顾客,2:商家,3:超级管理员',
    create_time datetime default null,
    last_edit_time datetime default null,
    primary key(user_id)
);

2.建微信账号表 tb_wechat_auth 

 1 create table tb_wechat_auth(
 2     wechat_auth_id int(10) auto_increment,
 3     user_id int(10) not null,
 4     open_id varchar(1024) not null,
 5     create_time datetime default null,
 6     primary key(wechat_auth_id),
 7     constraint fk_wechatauth_profile foreign key(user_id)
 8     references tb_person_info(user_id),
 9     unique key(open_id)
10 );

出现错误提示:[Err] 1071 - Specified key was too long; max key length is 767 bytes

错误地方:

  open_id varchar(1024) not null

原因分析:
   数据库表采用utf8编码,其中varchar(1024)的column进行了唯一键索引,而mysql默认情况下单个列的索引不能超过767位(不同版本可能存在差异)
  于是utf8字符编码下,1024*3 byte 超过限制676位,所以才会报错。由此反推,676/3 ≈ 225 ,所以varchar最高值为255。
 
3.验证原因分析
  第一步:修改为256试试
 1 create table tb_wechat_auth(
 2     wechat_auth_id int(10) auto_increment,
 3     user_id int(10) not null,
 4     open_id varchar(256) not null,
 5     create_time datetime default null,
 6     primary key(wechat_auth_id),
 7     constraint fk_wechatauth_profile foreign key(user_id)
 8     references tb_person_info(user_id),
 9     unique key(open_id)
10 );

仍然报错:[Err] 1071 - Specified key was too long; max key length is 767 bytes

  第二步:修改为255试试
 1 create table tb_wechat_auth(
 2     wechat_auth_id int(10) auto_increment,
 3     user_id int(10) not null,
 4     open_id varchar(255) not null,
 5     create_time datetime default null,
 6     primary key(wechat_auth_id),
 7     constraint fk_wechatauth_profile foreign key(user_id)
 8     references tb_person_info(user_id),
 9     unique key(open_id)
10 );

原因分析正确,建表成功!展示如下

1.栏位

2.索引

3.外键

总结:varchar(n),n≤255

 
 
 
原文地址:https://www.cnblogs.com/zui-ai-java/p/10405274.html