表1:

Field Type Null Key Default Extra
UserID int(11) NO PRI NULL auto_increment
Password varchar(20) NO
Username varchar(25) NO
Email varchar(60) NO

表2:

Field Type Null Key Default Extra
UserID int(11) NO MUL
PostID int(11) NO PRI NULL auto_increment
Title varchar(50) NO
Summary varchar(500) NO

错误:

com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: 无法添加或更新子行:外键约束失败 (myapp/table2,约束table2_ibfk_1外键(UserID)) 引用表1 (UserID))

我做错了什么?我读了http://www.w3schools.com/Sql/sql_foreignkey.asp,我不知道有什么问题。


当前回答

我还得到了这个错误:“不能添加或更新一个子行:一个外键约束失败”。我得到了错误时,添加一个新行到父表

问题是外键约束是在父表上定义的,而不是在子表上。

其他回答

我花了一段时间才想明白。简单地说,引用另一个表的表中已经有数据,它的一个或多个值在父表中不存在。

如。 表2的数据如下:

UserID    PostID    Title    Summary
5         1         Lorem    Ipsum dolor sit

表1

UserID    Password    Username    Email
9         ********    JohnDoe     john@example.com

如果尝试ALTER table2并添加外键,则查询将失败,因为UserID=5在Table1中不存在。

You're getting this error because there are some value int table2.UserID that is not exists on table1.UserID (I guess that you have setted table2.UserID value manualy before you created this foreign key). One example for this scene: table1.UserID get values 1,2,3 and table2.UserID get values 4 (add by manual). So when you make a foreign key, they can't find UserID = 4 from table1 and the error will ocurse. To fix this error, just remove UserID = 4 from table2 or you can empty both of them and then create the foreign key and. Good luck!

我刚遇到同样的问题,解决方法很简单。

您正在尝试在子表中添加父表中不存在的id。

检查好,因为InnoDB有一个bug,有时会增加auto_increment列而不增加值,例如INSERT…关于重复的密钥

一个简单的破解方法是在对表执行任何操作之前禁用外键检查。简单查询

SET FOREIGN_KEY_CHECKS=0

这将禁用与任何其他表的外键匹配。处理完表后,再次启用它

SET FOREIGN_KEY_CHECKS=1

这对我来说很管用。


请注意,当你这样做时,你进入了危险区。虽然确实存在有效的用例,但只有当您确定了解其含义时才应该这样做。

如果您添加了复选框NOT NULL的列 你会惊讶地发现所有的行都是0, 当你尝试添加外键时,可能你在foreign table2中没有值为0的行,所以mysql错误弹出显示