外键约束
涉及到两个表:父表,子表;主表,副表;
–设计一个班级表
create table classes(
id int primary key,
name varchar(20)
);
--学生表 // 学生表的class_id 来自于 班级表的id字段
create table students(
id int primary key,
name varchar(20),
class_id int,
foreign key (class_id) references classed(id)
);
向班级表插入数据:
insert into classes values(1,'一班');
insert into classes values(2,'二班');
insert into classes values(3,'三班');
insert into classes values(4,'四班');
+----+------+
| id | name |
+----+------+
| 1 | 一班 |
| 2 | 二班 |
| 3 | 三班 |
| 4 | 四班 |
+----+------+
向学生表插入数据:
insert into students values(1001,'张三',1);
insert into students values(1002,'张三',2);
insert into students values(1003,'张三',3);
insert into students values(1004,'张三',4);
---上述插入成功
insert into students values(1005,'张三',5);
Cannot add or update a child row: a foreign key constraint fails
(`dsname`.`students`, CONSTRAINT `students_ibfk_1` FOREIGN KEY (`class_id`) REFERENCES `classes` (`id`))
– 1.主表classes中没有的数据值,在副表students中是不可使用的。
– 2. 主表中的记录被副表引用,是不可以删除的。
delete from classes where id = 4;
Cannot **delete or update a parent row**: a foreign key constraint fails (`dsname`.`students`, CONSTRAINT `students_ibfk_1` FOREIGN KEY (`class_id`) REFERENCES `classes` (`id`))