表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,我不知道有什么问题。


当前回答

当您希望添加外键时,该错误会发生在父表的主键中不存在的值。必须确保table2中的新外键UserID具有table1主键中存在的值,有时默认为null或等于0。

你可以先用一个存在于table1的主键中的值来更新table2中外键的所有字段。

update table2 set UserID = 1 where UserID is null

如果要添加不同的userid,则必须使用所需的值修改每行。

其他回答

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!

İf你使用mysql索引或表之间的关系,首先你删除列(例如:city_id),并创建新的列同名(例如:city_id)。然后再试一次……

我也遇到过类似的问题。您正在尝试对一个有内容且列不可空的表应用外键。你有两个选择。

使要应用外键约束的列为可空。这样就可以应用外键,知道某些字段可以为空。(这就是我所做的。) 创建要应用外键约束的列,编写查询将外键插入该列,然后应用外键约束。(没有尝试过,但应该可以工作)

子表外键约束失败

这个问题可能是由以下原因引起的:

如果你在Spring mvc中这样做,你需要显式地描述id类型,因为有时mysql无法识别id的类型。所以你显式设置为在你的实体class@GeneratedValue(策略= GenerationType.IDENTITY)

我发现了另一个奇怪的情况:如果你无意中创建了一个从InnoDB表到MyISAM表的外键,MySQL在插入时抛出这个错误,即使数据是有效的。

参见http://nick.zoic.org/art/mysql-foreign-key-error/