数据库(MySQL)基础:约束

一、概述

1.概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据。

2.目的:保证数据库中数据的正确、有效性和完整性。

3.分类

|------|------------------------------|-------------|
| 约束 | 描述 | 关键字 |
| 非空约束 | 限制该字段的数据不能为null | not null |
| 唯一约束 | 保证该字段的所有数据都是唯一、不重复的 | unique |
| 主键约束 | 主键是一行数据的唯一标识,要求非空且唯一 | primary key |
| 默认约束 | 保存数据时,如果未指定该字段的值,则采用默认值 | default |
| 检查约束 | 保证字段值满足某一个条件 | check |
| 外键约束 | 用来让两张表的数据之间建立连接,保证数据的一致性和完整性 | foreing key |

注意:约束是作用于表中字段上的,可以在创建表 / 修改表的时候添加约束。

二、约束演示

根据需求,来完成表结构的创建

|--------|--------|-------------|---------------|------------------------------|
| 字段名 | 字段含义 | 字段类型 | 约束条件 | 约束条件 |
| id | ID唯一标识 | int | 主键,并且自动增长 | primary key , auto_increment |
| name | 性别 | varchar(10) | 不为空,并且唯一 | not null , unique |
| age | 年龄 | int | 大于0,并且小于等于120 | check |
| status | 状态 | char(1) | 如果没有指定该值,默认为1 | default |
| gender | 性别 | char(1) | 无 | |

大家不妨先自己动手尝试尝试,我就先把答案放在下方啦!

复制代码
create table if not exists user(
    id int primary key auto_increment comment '主键',
    name varchar(10) not null unique comment '姓名',
    age int check(age>0 && age<120) comment '年龄',
    status char(1) default '1' comment '状态',
    gender char(1) comment '性别'
)comment '用户表';

建立的表结构截图如下:

三、外键约束

1.概念:外键用来让两张表的数据之间建立连接,从而保证数据的一致性和完整性。

注意:目前上述的两张表,在数据库层面,并未建立外键关联,所以是无法保证数据的一致性和完整性的。

在开始之前,我先来进行表结构的创建,代码如下,大家可以自行参考

复制代码
create table if not exists dept(
    id int auto_increment comment 'ID' primary key,
    name varchar(50) not null comment '部门名称'
)comment '部门表';
insert into dept(name) values('研发部'),('市场部'),('财务部'),('销售部'),('总经办');
create table if not exists dept_id(
    id int auto_increment comment 'ID' primary key,
    name varchar(50) not null comment '姓名',
    age int comment '年龄',
    job char(10) comment '职位',
    salary int comment '薪资',
    entrydate date comment '入职时间',
    managerid int comment '直属领导ID',
    dept_id int comment '部门ID'
)comment '员工表';

insert into emp(name,age,job,salary,entrydate,managerid,dept_id) values
        ('金庸',66,'总裁','20000','2000-01-01',null,5),
        ('张无忌',20,'项目经理','12500','2005-12-05',1,1),
        ('杨逍',33,'开发','8400','2000-11-03',2,1),
        ('韦一笑',48,'开发','11000','2002-02-05',2,1),
        ('常遇春',43,'开发','10500','2004-09-07',3,1);

创建好的表如下:

接下来,我们来建立外键关联,以此来保证数据的一致性和完整性。

2.外键约束

2.1添加外键

create table 表名(

字段名 数据类型 ,

...

constraint\] \[外键名称\] foreign key (外键字段名) references 主表(主表列名) ); alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(主表列名);

复制代码
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);

大家看emp表前后的区别

2.2删除外键

alter table 表名 drop foreign key 外键名称 ;

复制代码
alter table emp drop foreign key fk_emp_dept_id;

2.3删除 / 更新行为

|-------------|--------------------------------------------------------------------------|
| 行为 | 说明 |
| no action | 当在父表中删除 / 更新对应记录时,首先检查记录是否有对应外键,如果有则不允许删除 / 更新。(与restrict一致) |
| restrict | 当在父表中删除 / 更新对应记录时,首先检查记录是否有对应外键,如果有则不允许删除 / 更新。(与no action一致) |
| cascade | 当在父表中删除 / 更新对应记录时,首先检查记录是否有对应外键,如果有,则也删除 / 更新外键在子表中的记录。 |
| set null | 当在父表中删除 / 更新对应记录时,首先检查记录是否有对应外键,如果有,则设置子表中该外键值为 null (这就要求该外键允许取 null )。 |
| set default | 父表有变更时,子表将外键列设置成一个默认的值。 |

alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表名(主表列名) on update cascade on delete cascade;

-- cascade

复制代码
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade;

-- set null

复制代码
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update set null on delete set null;

本节课的内容到此结束啦,我们下期再见!

相关推荐
IvorySQL7 分钟前
双星闪耀温哥华:IvorySQL 社区两项议题入选 PGConf.dev 2026
数据库·postgresql·开源
ma_king3 小时前
入门 java 和 数据库
java·数据库·后端
jiayou646 小时前
KingbaseES 实战:审计追踪配置与运维实践
数据库
随风飘的云7 小时前
mysql的innodb引擎对可重复读做了那些优化,可以避免幻读
mysql
NineData18 小时前
NineData 迁移评估功能正式上线
数据库·dba
NineData1 天前
数据库迁移总踩坑?用 NineData 迁移评估,提前识别所有兼容性风险
数据库·程序员·云计算
赵渝强老师1 天前
【赵渝强老师】PostgreSQL中表的碎片
数据库·postgresql
全栈老石1 天前
拆解低代码引擎核心:元数据驱动的"万能表"架构
数据库·低代码
倔强的石头_2 天前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库
jiayou643 天前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库