[英]Cannot add foreign key to table
I have a problem to add foreign key to existing table, I always get error 我有一个问题是将外键添加到现有表,我总是得到错误
ERROR 1005(HY000): Can't create table '#sql-a1f-b84' (errno: 150)
I tried like 我尝试过
ALTER TABLE alliances ADD CONSTRAINT fk_alliance_id FOREIGN KEY (alliance_id) references alliances(id);
When I do DESCRIBE alliances;
当我做了DESCRIBE alliances;
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
name bigint(2) YES NULL
When I do DESCRIBE alliance_invitation;
当我做DESCRIBE alliance_invitation;
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
alliance_id int(11) NO
Can anyone tell me what is a problem ? 谁能告诉我什么是问题?
you need to first CREATE INDEX
on your FK column alliance_id
. 你需要首先在你的FK列alliance_id
上CREATE INDEX
。 Mysql needs an index to preexist in order to add a constraint on it. Mysql需要一个预先存在的索引才能在其上添加约束。
try this: 试试这个:
ALTER TABLE `alliance_invitation` ADD INDEX ( `alliance_id` );
ALTER TABLE `alliance_invitation` ADD FOREIGN KEY ( `alliance_id` )
REFERENCES `alliances` ( `id` ) ON DELETE CASCADE ON UPDATE CASCADE;
You can change the CASCADE to anything else. 您可以将CASCADE更改为其他任何内容。 more info here 更多信息在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.