当前位置:网站首页>Mysql 外键详解(Foreign Key)
Mysql 外键详解(Foreign Key)
2022-08-03 05:22:00 【鱼丸丶粗面】
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;
边栏推荐
猜你喜欢
随机推荐
7.16(6)
Browser multi-threaded off-screen rendering, compression and packaging scheme
解析各种文本的年月日
处理异步事件的三种方式
中国生物反应器行业市场投资分析及前景预测报告2022~2028年
动态调整web主题(2) 萃取篇
Router-view
C语言简单实现三子棋小游戏
中国水产养殖行业市场投资分析及未来风险预测报告2022~2028年
Oracle 注释详解(--、/**/、rem)
关于semantic-ui的cdn失效问题(怎样通过本地引用semantic-ui)
Go (一) 基础部分3 -- 数组,切片(append,copy),map,指针
【XSS,文件上传,文件包含】
【编程学习新起点】记录写博客的第一天
pta a.1003 的收获
jsp通过form表单提交数据到servlet报404
嵌入式实验二
Sqli-labs-master shooting range 1-23 customs clearance detailed tutorial (basic)
pta a.1030的dijkstra+DFS方法
中国生物反应器行业发展现状及前景规划分析报告报告2022~2028年









