简体   繁体   English

无法创建外键约束

[英]unable to create a foreign key constraint

I have a clients, feedback and a repairs tables. 我有一个客户,反馈和维修表。 A client can give many feedbacks and have many repairs. 客户可以提供许多反馈并进行很多维修。 In the feedback table I have created a clientid column (added also index) and I am able to create a foreign key to the clientid column (primary key) of the clients table. 在反馈表中,我创建了一个clientid列(还添加了索引),并且能够为clients表的clientid列(主键)创建外键。

The problem is that I am unable to do the same with the repairs table. 问题是我无法对修理表做同样的事情。 Even though I have created a clientid column (indexed) within the repairs table and it has the same properties as the clientid within the clients table I get the following: 即使我在修复表中创建了一个clientid列(已建立索引),并且它具有与clients表中的clientid相同的属性,但我得到以下信息:

MySQL said: Documentation MySQL说:文档

#1452 - Cannot add or update a child row: a foreign key constraint fails ( ccsdb ., CONSTRAINT #sql-3f0_8e5_ibfk_1 FOREIGN KEY ( client_id ) REFERENCES clients ( client_id ) ON DELETE CASCADE ON UPDATE CASCADE) ccsdb无法添加或更新子行:外键约束失败( ccsdb 。,CONSTRAINT #sql-3f0_8e5_ibfk_1键( client_id )参考clientsclient_id )在更新#sql-3f0_8e5_ibfk_1

That error ( Cannot add or update a child row: a foreign key constraint fails ) is referenced in the MySQL FK Doc MySQL FK Doc中引用了该错误( Cannot add or update a child row: a foreign key constraint fails

To add a reference between 2 tables the condition must fit for existing data. 要在2个表之间添加引用,条件必须适合现有数据。

That means if you say table1.id = table2.id then all ids of table1 and table2 must match together. 这意味着,如果您说table1.id = table2.idtable1table2所有ID必须匹配。

To solve that you have to eliminate or fix those rows that don't match. 为了解决这个问题,您必须消除或修复那些不匹配的行。
Example: 例:

table1.id  |  table2.fk
   1       |       1      ok 
   2       |     null     error
   3       |       4      error if id 4 is not in table1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM