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


当前回答

子表外键约束失败

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

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

其他回答

表中是否包含任何现有数据? 如果是,请尝试清除要添加外键的表中的所有数据。 然后再次运行代码(添加外键)。

这个问题我遇到过很多次了。当您想在现有表上添加外键时,清除表中的所有数据可以工作。

希望这有用:)

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!

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

只是一点点修复: 使JoinColumn在Table1中为'nullable=true', 'UserID'字段在Table2中为'insertable=false'和'nullable=true'。

表1实体:

@OneToMany(targetEntity=Table2.class, cascade = CascadeType.ALL)
@JoinColumn(name = "UserID", referencedColumnName = "UserID", nullable = true)
private List<Table2> table2List;

表2实体:

@Column(insertable = false, nullable = true)
private int UserID;

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

如。 表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中不存在。