CREATE TABLE LECTURER
(LectID VARCHAR(12) NOT NULL,
Name VARCHAR(30) NOT NULL,
Email VARCHAR(30) NOT NULL,
Faculty VARCHAR(20) NOT NULL,
CONSTRAINT LECTURER_pkey PRIMARY KEY (LectID));
CREATE TABLE NOK
(LectID VARCHAR(12) NOT NULL,
Name VARCHAR(30) NOT NULL,
DOB DATE NOT NULL,
CONSTRAINT NOK_pkey PRIMARY KEY (LectID, Name, DOB),
CONSTRAINT NOK_fkey FOREIGN KEY (LectID) references LECTURER (LectID));
我在mysql中创建了2个表,如何确保当LECTURER
表中的行被删除时,来自NOK
的相关行也会被删除?
答案 0 :(得分:2)
您需要在ON DELETE CASCADE
表中使用NOK
。
更改
CONSTRAINT NOK_fkey FOREIGN KEY (LectID) references LECTURER (LectID)
到
CONSTRAINT NOK_fkey FOREIGN KEY (LectID) references LECTURER (LectID)
ON DELETE CASCADE
已编辑==
在执行上述脚本之前,您需要在下面执行,这样您就不会收到任何错误。
ALTER TABLE NOK DROP FOREIGN KEY NOK_fkey;