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