3. 约束

3. 约束

  • 概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据。
  • 目的:保证数据库中数据的正确、有效性和完整性。
  • 分类:
约束 描述 关键字
非空约束 限制该字段的数据不能为null NOT NULL
唯一约束 保证该字段的所有数据都是唯一、不重复的 UNIQUE
主键约束 主键是一行数据的唯一标识,要求非空且唯一 PRIMARY KEY
默认约束 保存数据时,如果未指定该字段的值,则采用默认值 DEFAULT
检查约束(8.0.1版本后) 保证字段值满足某一个条件 CHECK
外键约束 用来让两张图的数据之间建立连接,保证数据的一致性和完整性 FOREIGN KEY

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

1. 常用约束

约束条件 关键字
主键 PRIMARY KEY
自动增长 AUTO_INCREMENT
不为空 NOT NULL
唯一 UNIQUE
逻辑条件 CHECK
默认值 DEFAULT

例子:

1
2
3
4
5
6
7
8
9
10
11
create table user(
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名',
age int check(age > 0 and age < 120) comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) comment '性别'
)comment '用户表';

insert into user(name, age, status, gender) values ('Tom1', 19, '1', '男'),('Tom2', 25, '0', '男'),('Tom3', 20, '1', '男');


2. 外键约束

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

  • 添加外键:

1
2
3
4
5
6
7
8
9
CREATE TABLE 表名(
字段名 字段类型,
...
[CONSTRAINT] [外键名称] FOREIGN KEY(外键字段名) REFERENCES 主表(主表列名)
);
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名) REFERENCES 主表(主表列名);

-- 例子
alter table emp2 add constraint fk_emp2_dept_id foreign key(dept_id) references dept(id);
  • 删除外键:
1
2
ALTER TABLE 表名 DROP FOREIGN KEY 外键名;
alter table emp2 drop foreign key fk_emp2_dept_id;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

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 emp2(
id int auto_increment comment 'id' primary key ,
name varchar(50) not null comment '姓名',
age int comment '年龄',
job varchar(20) comment '职位',
salary int comment '薪资',
enterdate date comment '入职时间',
managerid int comment '直属领导id',
dept_id int comment '部门id'
)comment '员工表';

insert into emp2(id, name, age, job, salary, enterdate, managerid, dept_id)
VALUES (1,'金庸',66,'总裁',20000,'2000-01-01',null,5),
(2,'张无忌',20,'项目经理',12500,'2005-12-05',2,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);

删除/更新行为

行为 说明
NO ACTION 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新(与RESTRICT一致)
RESTRICT 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新(与NO ACTION一致)
CASCADE 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则也删除/更新外键在子表中的记录
SET NULL 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则设置子表中该外键值为null(要求该外键允许为null)
SET DEFAULT 父表有变更时,子表将外键设为一个默认值(Innodb不支持)

更改删除/更新行为:

1
2
3
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段) REFERENCES 主表名(主表字段名) ON UPDATE 行为 ON DELETE 行为;
alter table emp2 add constraint fk_emp2_dept_id foreign key (dept_id ) references dept(id) on update cascade on delete cascade;
alter table emp2 add constraint fk_emp2_dept_id foreign key (dept_id ) references dept(id) on update set null on delete set null;

3. 约束
http://binbo-zappy.github.io/2024/11/26/MySQL/3-约束/
作者
Binbo
发布于
2024年11月26日
许可协议