级联删除操作(了解)
如果想实现删除主表数据的同时,也删除掉从表数据,可以使用级联删除操作
级联删除 ON DELETE CASCADE
代码示例:
删除 employee表,重新创建,添加级联删除
-- 重新创建添加级联操作 CREATE TABLE employee( eid INT PRIMARY KEY AUTO_INCREMENT, ename VARCHAR(20), age INT, dept_id INT, CONSTRAINT emp_dept_fk FOREIGN KEY(dept_id) REFERENCES department(id), -- 添加级联删除 ON DELETE CASCADE ); -- 添加数据 INSERT INTO employee (ename, age, dept_id) VALUES ('张百万', 20, 1); INSERT INTO employee (ename, age, dept_id) VALUES ('赵四', 21, 1); INSERT INTO employee (ename, age, dept_id) VALUES ('广坤', 20, 1); INSERT INTO employee (ename, age, dept_id) VALUES ('小斌', 20, 2); INSERT INTO employee (ename, age, dept_id) VALUES ('艳秋', 22, 2); INSERT INTO employee (ename, age, dept_id) VALUES ('大玲子', 18, 2); -- 删除部门编号为2 的记录 DELETE FROM department WHERE id = 2;
运行效果:
员工表中 外键值是2的记录,也被删除了