首页 > 解决方案 > 如何解决此 MySQL Foreign Key Constraint Fails 错误?数据看起来正确

问题描述

我发现很难在 MySQL 中本地化这个错误。我有一个名为“社区”的表和另一个名为“消息”的表。“消息”表有一个名为“to_community_id”的外键列。我在“社区”表中有几个社区。当我尝试插入具有某些社区 ID(有效)的消息时,查询失败并出现“外键约束失败”错误。一些社区 ID 有效。其余社区数据完全相同。什么可能导致此错误?

架构:

Community:
FIELD       TYPE            NULL    KEY     EXTRA
id          int(10) unsignedNO      PRI     auto_increment
name        varchar(255)    YES         
address     varchar(255)    YES         
city        varchar(255)    YES         
country     varchar(255)    YES         
phone       varchar(255)    YES         
coordinates point           YES         
data        json            YES         
settings    json            YES         
private     tinyint(1)      YES         
deleted tinyint(1)          YES     



Message:

FIELD               TYPE               NULL KEY EXTRA
id                  int(10) unsigned    NO   PRI auto_increment
datetime            datetime            YES         
deleted             tinyint(1)          YES     
read                tinyint(1)          YES     
details             json                YES         
from_user_id        int(10) unsigned    YES 
to_user_id          int(10) unsigned    YES         
from_community_id   int(10) unsigned    YES     
to_community_id     int(10) unsigned    YES     
community_join_id   int(10) unsigned    YES 

外键约束:

CONSTRAINT_NAME                            TABLE_NAME   CONSTRAINT_TYPE
message_community_join_request_id_foreign   message     FOREIGN KEY
message_from_community_id_foreign           message     FOREIGN KEY
message_from_user_id_foreign                message     FOREIGN KEY
message_to_community_id_foreign             message     FOREIGN KEY
message_to_user_id_foreign                  message     FOREIGN KEY

插入语句:

insert into message (`from_user_id`,  `to_community_id`, `to_user_id`) 
values ( 1, 11, 2);

标签: mysql

解决方案


我会回答我自己的问题,因为尽管这个答案让我看起来像个白痴,但它可能会帮助同一条船上的其他人。

仔细查看外键,我注意到“to_community_id”字段的引用表是错误的。

修复它解决了这个问题。


推荐阅读