簡體   English   中英

MySQL InnoDB表添加外鍵errno:150

[英]MySQL InnoDB table adding foreign key errno:150

好吧,我有兩個桌子

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_evento是第三個名為publica_evento的表的外鍵,但與表publica_identificacao_publicacao的列一起也是外鍵。 identificacao 問題是,我必須通過鍵id_evento創建將publica_evento_grupopublica_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_grupoidentificacao_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_grupoidentificacao字段具有外鍵約束。 我們還說在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM