为什么现在大家都不用外键了(二)?
从表插入新行,其外键值不是主表的主键值便阻止插入;
从表修改外键值,新值不是主表的主键值便阻止修改;
主表删除行,其主键值在从表里存在便阻止删除(要想删除,必须先删除从表的相关行);
主表修改主键值,旧值在从表里存在便阻止修改(要想修改,必须先删除从表的相关行)。
主表删除行,连带从表的相关行一起删除;
主表修改主键值,连带从表相关行的外键值一起修改。
CREATE TABLE jiaolian(
`jiaolian_id` INT AUTO_INCREMENT,
`jiaolian_name` VARCHAR(30),
PRIMARY KEY (`jiaolian_id`));
CREATE TABLE xueyuan(
`xueyuan_id` INT AUTO_INCREMENT,
`jiaolian_id` INT,
`xueyuan_name` VARCHAR(30),
FOREIGN KEY (`jiaolian_id`) REFERENCES `jiaolian` (`jiaolian_id`),
PRIMARY KEY (`xueyuan_id`));
insert into jiaolian(jiaolian_name) values("司机老李");
insert into jiaolian(jiaolian_name) values("司机老林");
insert into xueyuan(jiaolian_id,xueyuan_name) values(1,"徒弟张三");
insert into xueyuan(jiaolian_id,xueyuan_name) values(2,"徒弟李四");
insert into xueyuan(jiaolian_id,xueyuan_name) values(3,"徒弟王五"); #error
delete from jiaolian where jiaolian_name="司机老李"; #error
delete from xueyuan where xueyuan_name="徒弟张三";
delete from jiaolian where jiaolian_name="司机老李";
相关文章