新增外键时报错:
错误代码: 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
);
发现操作成功:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。