MySQL的外键

外键(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)
);

备注:
关联外键的字段也可以为
constraint fk_u_d foreign key (part_id) references department(id) on delete cascade on update no action
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值