](https://img-blog.csdnimg.cn/21dd41dce63a4f2da07b9d879ad0120b.png#pic_center)
🌈个人主页: Aileen_0v0
🔥热门专栏: 华为鸿蒙系统学习|计算机网络|数据结构与算法
💫个人格言:“没有罗马,那就自己创造罗马~”
文章目录
- `外键约束`
-
- `添加外键的语法`
- `创建表的时候直接添加外键`
- `创建完表以后额外添加`
- `删除外键`
外键约束
含义
外键:
用来让两张表的数据之间建立连接,从而保证数据的完整性和一致性。
id | name | age | job | salary | entrydate | managerid | dept_id |
---|
1 | 金庸 | 66 | 总裁 | 20000 | 2000-01-01 | null | 5 |
2 | 张无忌 | 20 | 项目经理 | 12500 | 2005-12-05 | 1 | 1 |
3 | 杨逍 | 33 | 开发 | 8400 | 2000-11-03 | 2 | 1 |
4 | 韦一笑 | 48 | 开发 | 11000 | 2002-02-05 | 2 | 1 |
5 | 常遇春 | 43 | 开发 | 10500 | 2004-09-07 | 3 | 1 |
id | name |
---|
1 | 研发部 |
2 | 市场部 |
3 | 财务部 |
4 | 销售部 |
5 | 总经办 |
⚠️注意:上面两张表,在数据库层面,并未建立外键关联,所以无法保证数据的一致性和完整性。
1.准备好部门表
create table dept(id int auto_increment comment 'ID' primary key ,name varchar(50) not null comment '部门名称'
)comment '部门表';
insert into dept(id, name) VALUES (1,'研发部'),(2,'市场部'),(3,'财务部'),(4,'销售部'),(5,'总经办');

create table emp(id int auto_increment comment 'ID' primary key ,name varchar(50) not null comment '姓名',age int comment '年龄',job varchar(20) comment '职位',salary int comment '薪资',entrydate date comment '入职时间',managerid int comment '直属领导ID',dept_id int comment '部门ID'
)comment '员工表';insert into emp (id, name, age, job, salary, entrydate, managerid, dept_id) VALUES(1,'金庸',66,'总裁',2000,'2000-01-01',null,5),(2,'张无忌',20,'项目经理',12500,'2005-12-05',1,1),(3,'杨逍',33,'开发',8400,'2000-11-03',2,1),(4,'韦一笑',48,'开发',11000,'2002-02-05',2,1),(5,'常遇春',43,'开发',10500,'2004-09-07',3,1),(6,'小昭',19,'程序员鼓励师',6600,'2004-10-12',2,1);

分析
通过这两张表我们可以看出,他们之间存在逻辑关系。但是并未设置物理外键,这就无法保证数据的一致性和完整性。 |


如果我们把1号部门删了,但是员工表的数据海关连着1号表,这就会导致数据出现不完整性。 |

添加外键的语法
创建表的时候直接添加外键
create table 表名(字段名 数据类型,...[constraint] [外键名称] foreign key(外键字段名) references 主表(主表列表)
);
创建完表以后额外添加
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名);



⚠️报错显示:我们不能直接删除父表中id为1的记录,而子表中还有非常多的记录关联着父表中id为1的记录。 |
删除外键
alter table 表名 drop foreign key 外键名称;
alter table emp drop foreign key fk_emp_dept_id;

](https://img-blog.csdnimg.cn/0ee6c4ec414740b0a0404c5161cdadc7.gif#pic_center)
](https://img-blog.csdnimg.cn/cc002cbd5c414c5393e19c5e0a0dbf20.gif#pic_center#pic_center)