获取错误1451(23000):无法删除或更新父行:外键约束失败

时间:2016-02-20 20:15:53

标签: mysql sql-delete alter

我之前使用了以下代码来获得我想要的东西,但后来我添加了一些外键并且它搞砸了它:

DELETE FROM Faculty WHERE LastName LIKE 'Z%'

DELETE FROM Courses WHERE FirstYrOffered='1999'

我只是想从表中删除一个条目,但它无法正常工作。这就是我的表格的样子:

CREATE TABLE Faculty (
FacultyID int,
FirstName varchar(30),
LastName varchar(30),
EMail varchar(60),
BirthDate DATE,
Numbr_Courses int,
PRIMARY KEY (FacultyID)
);

CREATE TABLE Courses(
CourseID int,
CourseDisc varchar(4),
CourseNum varchar(4),
NumbrCred varchar(1),
FirstYrOffered int,
CourseTitle varchar(75),
PRIMARY KEY (CourseID)
);

CREATE TABLE Faculty_Courses(
InstanceID int,
FacultyID int,
CourseDisc varchar(4),
CourseID int,
CourseNum varchar(4),
CourseTitle varchar(75),
PRIMARY KEY (InstanceID),
FOREIGN KEY (FacultyID) REFERENCES Faculty(FacultyID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);

我已经查看了ALTER TABLE代码示例,但并不是很了解我在做什么。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

首先,您必须从Faculty_Courses中删除相应的记录,然后从教师和课程表中删除记录。或者,在外键上设置on delete cascade option