![](/img/trans.png)
[英]Adding table with FOREIGN KEY to a MySQL database causes errno 150
[英]MySQL InnoDB table adding foreign key errno:150
好吧,我有两个桌子
Field | Type | Null | Key | Default | Extra
id_evento_grupo int(10) unsigned NO PRI auto_increment
id_evento int(8) unsigned NO MUL
id_grupo int(8) unsigned NO MUL
identificacao varchar(55) NO
Field | Type | Null | Key | Default | Extra
id_evento int(8) unsigned NO PRI
identificacao varchar(55) NO PRI
publica_evento_grupo
。 id_evento
是第三个名为publica_evento的表的外键,但与表publica_identificacao_publicacao
的列一起也是外键。 identificacao
。 问题是,我必须通过键id_evento
创建将publica_evento_grupo与publica_identificacao_publicacao关联的外键,但是当我尝试使用identificacao
列创建另一个FK时,它将给出下面的errno
[Err] 1005 - Can't create table '#sql-1049_1980992' (errno: 150).
如您所见,表publica_identificacao_publicacao有两个PK,这就是必须2 FK才能关联它们的原因,我还没有创建索引,因为据我所知,我只需要在创建索引后添加FK id_evento
,然后我就可以在evento_grupo和identificacao_publicacao之间的id_evento列中创建FK 约束 ,我不知道为什么只有identificacao
列会出现此错误
编辑1:@RolandBouman我没有使用该命令的权限SHOW ENGINE INNODB STATUS
编辑2:@Geoff_Montee正确地传递了您传递的命令,以理解我为什么使用该结构,看看这个问题MySQL UNIQUE约束多列条件
没有实际的DDL,说起来并不容易。 我建议您这样做:
SHOW ENGINE INNODB STATUS;
您遇到此错误后立即。 在输出中,查找如下所示的部分:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
121026 22:40:18 Error in foreign key constraint of table test/#sql-154c_94:
foreign key(rid) references bla(id):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
您可以在其中找到有关外键定义出了什么问题的详细信息。
通常会发生该错误,因为引用表和被引用表之间存在类型不匹配。 在这种情况下,类型似乎匹配。
您是否考虑过对主组合键中的两个字段都施加约束? 您可能必须先删除id_evento
上的现有外键约束。
ALTER TABLE publica_evento_grupo ADD FOREIGN KEY
(id_evento, identificacao) REFERENCES
publica_identificacao_publicacao (id_evento, identificacao);
它好像在这种情况下,错误可能是因为您尝试将外键约束添加到只有一个复合主键的一部分 。
其他表中是否存在identificacao
? 为什么要只向组合主键的一部分添加外键约束?
这样想吧...
假设您确实在publica_evento_grupo
表中publica_evento_grupo
对identificacao
字段具有外键约束。 我们还说在publica_identificacao_publicacao
表中,您有(1, "some string")
和(2, "some string")
。 因此,如果删除(2, "some string")
,但将(1, "some string")
留在原处。 引用publica_evento_grupo
表中(1, "some string")
的publica_evento_grupo
抱怨,即使它们不应该!
因此,在我看来,您应该为所有主键添加外键约束,或者不添加任何约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.