MySQL InnoDB表添加外键错误:150

时间:2012-10-26 20:09:07

标签: mysql sql entity-relationship foreign-key-relationship indexing

好吧,我有两张桌子

publica_evento_grupo

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  

publica_identificacao_publicacao

Field | Type | Null | Key | Default | Extra
id_evento       int(8) unsigned NO  PRI     
identificacao   varchar(55)     NO  PRI     

publica_evento_grupoid_evento in是第三个名为 publica_evento 的表的外键,但也是一个外键以及表publica_identificacao_publicacao的列。identificacao。问题是,我必须通过键id_evento创建将 publica_evento_grupo publica_identificacao_publicacao 相关联的外键,但是当我尝试使用键identificacao创建另一个FK时列 [Err] 1005 - Can't create table '#sql-1049_1980992' (errno: 150). ,它给出了下面的错误

id_evento

正如你所看到的那样 publica_identificacao_publicacao 有两个PK,并且说明它必须是2 FK来联系它们的原因,我还没有创建索引,因为就我而言知道,我只需要在添加FK约束后创建索引,并且我能够在 evento_grupo identificacao_publicacao 之间的列identificacao创建FK约束。 ,我不知道为什么只有列{{1}}发出此错误

编辑1:@RolandBouman我没有使用该命令的权限SHOW ENGINE INNODB STATUS

编辑2:@Geoff_Montee实际上你通过的命令工作,以解释为什么我使用该结构看看这个问题MySQL UNIQUE Constraint multiple columns condition

2 个答案:

答案 0 :(得分:9)

没有实际的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.

您可以在那里找到有关外键定义有什么问题的详细信息。

答案 1 :(得分:0)

通常会发生该错误,因为引用表和引用表之间存在类型不匹配。在这种情况下,类型似乎匹配。

您是否考虑过对主要复合键中的两个字段都有约束?您可能必须首先删除id_evento上的现有外键约束。

ALTER TABLE publica_evento_grupo ADD FOREIGN KEY 
    (id_evento, identificacao) REFERENCES 
    publica_identificacao_publicacao (id_evento, identificacao);

似乎这种情况下的错误可能是因为您尝试仅将外键约束添加到复合主键的部分

identificacao是否存在于任何其他表中?为什么要仅将外键约束添加到复合主键的一部分?

以这种方式思考......

假设您在publica_evento_grupo表中确实有{/ 1}}字段中的外键约束。我们也在identificacao表格中说publica_identificacao_publicacao(1, "some string")。因此,如果您删除(2, "some string"),请将(2, "some string")留在原位。引用(1, "some string")表格中(1, "some string")的行会抱怨,即使他们不应该抱怨!

因此,我觉得您应该为所有主键添加外键约束,或者不添加任何主键。