新增外键时报错:错误代码: 1215 Cannot add foreign key constraint 表key_list:CREATE TABLE key_list (server_app_id INT
新增外键时报错:
错误代码: 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
);
发现操作成功:
--结束END--
本文标题: 错误代码: 1215 Cannot add foreign key constraint
本文链接: https://lsjlt.com/news/41114.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0