如何解决此 MySQL 外键约束失败错误?数据看起来是正确的



我发现很难在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);

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

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

修复它解决了问题。

最新更新