Mysql 外键详解(Foreign Key)

本文详细介绍了数据库中外键约束的使用,包括在创建表和修改表时如何添加外键约束,以及如何删除外键约束。通过示例展示了如何在`student_info`表中引用`sex`表的主键,确保数据的一致性和完整性。
摘要由CSDN通过智能技术生成

1 概述

外键
引用:该表 列名 对应其它表的 主键
约定:列名、数据类型、精度 均保持一致
添加:创建表 和 修改表时均可

2 语法

constraint 约束名 foreign key (字段名1, 字段名n)
references 主表名 (主键列1, 主键列n)

sex 性别基表

字段名称数据类型说明
sex_codechar(1)性别代码
sex_descchar(2)性别描述

student_info 学生信息表

字段名称数据类型说明
snoint学号
namevarchar(50)姓名
sex_codechar(1)性别代码
create_datedate创建时间

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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼丸丶粗面

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值