表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中创建外键之前在表1中插入了一行,则会得到一个外键约束错误,因为在表1中自动增量值为2,在表2中为1。要解决这个问题,您必须截断表1并将自动增量值设置为1。然后可以添加表2。

其他回答

确保插入到外键的值存在于父表中。这对我很有帮助。例如,如果将user_id = 2插入到表中。2、但表。1没有user_id = 2,那么约束将抛出一个错误。准确地说,我的错误代码是#1452。希望这能帮助其他有同样问题的人!

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

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

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!

你得到这个错误是因为你试图添加/更新一行到table2,没有有效的值为UserID字段基于当前存储在table1的值。如果你发布更多的代码,我可以帮助你诊断具体的原因。

另一个奇怪的情况给了我这个错误。我错误地将外键引用到id主键。这是由错误的alter表命令引起的。我通过查询INFORMATION_SCHEMA表发现了这一点(参见这个stackoverflow答案)

该表非常混乱,任何ALTER table命令都无法修复。我终于放下桌子,重新组装。这消除了integrityError。