-- 1. 外键概念 -- 外键:如果一个字段的值是另外一个表的主键,这个字段就叫外键 -- 外键约束:要求一个字段的值只能是关联的主键的值 -- 2. 对应关系 -- 如果两个表需要通过外键建立对应关系,需要从数量上确定具体的对应关系: -- 一对一 外键可以添加在两张表的任意一张表中 -- 一对多 外键只能放在多的那张表中 -- 多对多 必须创建中间表,在中间表中添加两个外键 create table if not exists `t_coollege`( `col_id` int not null unique auto_increment comment '学院ID', `col_name` varchar(20) not null comment '学院名称', `col_intro` varchar(200) comment '学院介绍', primary key(`col_id`) ); -- 3. 创建表的时候添加外键 -- 第一步,创建外键对应的字段,字段名可以随意,但是字段的类型必须和他依赖的主键的类型一模一样 -- 第二步,添加外键约束:constraint 外键约束名 foreign key (外键字段) references 表名(主键字段) create table if not exists `t_students`( `stu_id` int not null unique auto_increment comment '学生ID', `stu_name` varchar(10) not null comment '学生姓名', `stu_birth` timestamp , `stu_sex` tinyint default 1 comment '性别', `sti_coollege` int comment '学生所在学院的ID编号', constraint fk_students_college foreign key (`sti_coollege`) references `t_coollege`(`col_id`) ); -- 4. 修改表的时候添加外键约束 create table if not exists t_jumin( `id` int not null unique auto_increment, `name` varchar(10) not null, `tel` char(11), primary key(`id`) ); create table if not exists t_dog( `dog_id` int not null unique auto_increment, `dog_breed` varchar(10), `dog_sex` tinyint default 0, `dog_weight` decimal(4,2), primary key(`dog_id`) ); -- 添加外键字段 alter table `t_dog` add `master` int; -- 添加外键约束 alter table `t_dog` add constraint fk_dog_jumin foreign key (`master`) references `t_jumin`(`id`); -- 删除外键约束 alter table `t_dog` drop foreign key fk_dog_jumin;
04.外键约束
本节1647字2025-04-14 20:17:15