外键约束的注意事项(设置外键级联解决不能同时删除,修改数据的问题)
1、添加数据
先添加主表中的数据,再添加从表中的数据
2、删除数据
先删从表中的数据,再删主表中的数据
3、修改数据
如果主表中的主键被从表引用了,不能修改此主键的值
-- 外键约束的使用细节:
-- 1、删除主表中的数据:报错
delete from department where id=10; -- 原因:外键表中还有引用数据 (解决方案:先删除从表中的数据,再删除主表中的数据)
-- 2 、修改主表中主键字段下的数据 : 报错
update department set id = 10 where id=1; -- 原因:外键表中还有引用数据
#修改从表中的外键约束
alter table employee drop foreign key FK_employee_dept_id;
-- 给外键约束添加:级联更新、级联删除
alter table employee add
constraint FK_employee_dept_id foreign key(dept_id) references department(id)
on DELETE cascade on update cascade ;