码迷,mamicode.com
首页 > 其他好文 > 详细

错误代码: 1215 Cannot add foreign key constraint

时间:2018-03-28 16:45:35      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:mysql   1215   foreign key   index   

新增外键时报错:
错误代码: 1215 Cannot add foreign key constraint

表key_list:
CREATE TABLE key_list (
server_app_id INT(11) NOT NULL ,
server_name CHAR(13) NOT NULL ,
PRIMARY KEY (server_app_id)
) ENGINE=INNODB DEFAULT CHARSET=utf8

表for_list:
CREATE TABLE for_list (
for_id INT(11) NOT NULL,
for_name CHAR(13) NOT NULL,
PRIMARY KEY (for_id)
) ENGINE=INNODB DEFAULT CHARSET=utf8

在表key_list中新增外键server_app_id_ibfk:
ALTER TABLE key_list ADD CONSTRAINT server_app_id_ibfk FOREIGN KEY (server_app_id) REFERENCES for_list (for_id);
执行正常

在表key_list中新增外键server_name_id_ibfk:
ALTER TABLE key_list ADD CONSTRAINT server_name_id_ibfk FOREIGN KEY (server_name) REFERENCES for_list (for_name);
执行报错。错误代码: 1215 Cannot add foreign key constraint

原因:
在新增外键时,关联表(for_list)中的相关字段(for_name)必须为index

解决:
for_list表for_name字段新增索引
ALTER TABLE for_list ADD INDEX for_index_name(for_name);

再次执行新增外键操作:
ALTER TABLE key_list ADD CONSTRAINT server_name_id_ibfk FOREIGN KEY (server_name) REFERENCES for_list (for_name);
发现操作成功:
技术分享图片

错误代码: 1215 Cannot add foreign key constraint

标签:mysql   1215   foreign key   index   

原文地址:http://blog.51cto.com/3241766/2092028

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!