MySQL的外键

来源:互联网 发布:钢铁进出口数据 编辑:程序博客网 时间:2024/06/05 17:13

外键(foreign key)作用:
用于约束处于关系内的实体
增加从表记录时,是否有与之对应的主表记录,如果有,则可以添加,没有则会 报错。
创建外键的语法:

alter table 从表 add constraint 外键名称 foreign key 从表(从表字段) references 主表(主表字段)

删除外键的语法:

alter table 表名 drop foreign key 外键名称

以员工表和部门表为例:
一、主表为部门表(4个部门)

create table department(id int not null auto_increment primary key,caption varchar(20) not null comment '部门');insert into department(caption) values('市场部'),('研发部'),('UI'),('运营');

二、从表为员工表

create table users (id int not null auto_increment primary key,name varchar(20),age int unsigned not null ,part_id int  );insert into users (name,age,part_id) values ('tom',26,4),('kerry',21,2),('san',25,3);

三、在从表(用户表)中创建外键,将用户表中的part_id和部门表中的id做一个关联

alter table users add constraint fk_u_d foreign key users(part_id) references department(id);

四、创建好外键,这样就将用户表的part_id和部门表的id做了一个关联,当我们在用户表中插入part_id不在部门表id的字段时,就会报错

这里写图片描述

五、当然我们在创建表的时候,可以直接把外键加进去

create table department(id int not null auto_increment primary key,caption varchar(20) not null comment '部门');create table users (id int not null auto_increment primary key,name varchar(20),age int unsigned not null ,part_id int  ,constraint fk_u_d foreign key (part_id) references department(id),);
原创粉丝点击