1

嗯,我有两张桌子

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_grupo. id_eventoin 是第三个名为publica_evento的表的外键,但也是与表的列一起的外键publica_identificacao_publicacaoidentificacao. 问题是,我必须通过 key 创建将publica_evento_grupopublica_identificacao_publicacao相关联的外键id_evento,但是当我尝试使用 column 创建另一个 FK 时identificacao,它会给出下面的 errno

 [Err] 1005 - Can't create table '#sql-1049_1980992' (errno: 150).

如您所见,表publica_identificacao_publicacao有两个 PK,这就是它必须是 2 个 FK 才能关联它们的原因,我还没有创建索引,因为据我所知,我只需要在之后创建索引添加 FK 约束,我能够为eventto_grupoidentificacao_publicacaoid_evento之间的列创建 FK 约束,我不知道为什么只有该列给出此错误identificacao

编辑 1:@RolandBouman 我无权使用该命令 SHOW ENGINE INNODB STATUS

编辑 2:@Geoff_Montee 实际上你传递的命令有效,不明白为什么我使用那个结构看看这个问题MySQL UNIQUE Con​​straint multiple columns condition

4

2 回答 2

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.

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

于 2012-10-26T20:43:55.600 回答
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表中对identificacao字段本身有一个外键约束。让我们在publica_identificacao_publicacao表中说你有(1, "some string")(2, "some string")。因此,如果您删除(2, "some string"),但保留(1, "some string")其位置。表中引用的行(1, "some string")publica_evento_grupo抱怨,即使它们不应该!

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

于 2012-10-26T20:21:19.990 回答