当父 table 中的行被删除时,从子 table 中删除行

Delete row from child table when a row from parent table gets deleted

   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 table ,我如何确定 LECTURER table 中的行从 NOK 中删除关联行也应该被删除?

您需要在 NOK table 中使用 ON DELETE CASCADE

改变

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;