从父表中删除一行时,从子表中删除行

时间:2017-10-01 05:19:48

标签: mysql sql-delete alter-table alter

   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的相关行也会被删除?

1 个答案:

答案 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;