1 概述
2 语法
constraint 约束名 foreign key (字段名1, 字段名n)
references 主表名 (主键列1, 主键列n)
sex 性别基表
字段名称 | 数据类型 | 说明 |
---|---|---|
sex_code | char(1) | 性别代码 |
sex_desc | char(2) | 性别描述 |
student_info 学生信息表
字段名称 | 数据类型 | 说明 |
---|---|---|
sno | int | 学号 |
name | varchar(50) | 姓名 |
sex_code | char(1) | 性别代码 |
create_date | date | 创建时间 |
2.1 创建表时,添加外键约束
create table sex (
sex_code char(1) not null comment '性别代码',
sex_desc char(2) not null comment '性别描述',
primary key(sex_code)
) comment '性别基表';
create table student_info (
sno int not null comment '学号',
name varchar(50) not null comment '姓名',
sex_code char(1) comment '性别代码',
create_date date not null comment '创建时间',
primary key(sno),
constraint fk_si_sex foreign key(sex_code)
references sex(sex_code)
) comment '学生信息表';
2.2 修改表时,添加外键约束
-- 前提:
-- 从表中外键列中的数据必须与主表中主键列中的数据一致
-- 或者是没有数据(null)
alter table 表名 add constraint 外键名
foreign key(列名) references 主表名 (列名);
alter table student_info add constraint fk_si_sex_new
foreign key(sex_code) references sex(sex_code);
2.3 删除外键约束
alter table 表名 drop foreign key 外键约束名;
alter table student_info drop foreign key fk_si_sex;