关于数据库约束
1.概述
- 数据库约束是用于限制和保护数据完整性的规则。
- 它们定义了在数据库中存储数据时须遵守的条件。
- 以确保数据的一致性和准确性。
2.分类(五大约束)
- 非空约束
not null
:要求一个字段的值不能为空。 - 唯一约束
unique
:- 要求在一个或多个字段上的值是唯一的。
- 添加唯一约束的列上也会自动创建唯一索引。
- 主键约束
primary key
- 用于唯一标识数据库表中每个记录的字段或字段组合。
- 要求主键值在表中是唯一且非空的。
- 主表中增加数据后,从表才可以添加数据。
- 外键约束
foreign key
- 用于建立表之间的关系。
- 该字段的值必须匹配另一个表中的主键或唯一键的值。
- 可以确保引用完整性,即保证相关表之间的数据一致性。
- 检查约束
check
- 用于定义字段上的条件表达式。
- 只有满足该条件的值才能被插入或更新到数据库中。
3.其他
- 约束在创建数据库表时通过使用DDL语句进行指定。
- 约束数据库管理系统自动执行和维护。
- 通过使用约束,可以提高数据库的数据完整性、一致性和安全性。
约束介绍
0.示例准备
-
创建数据库 company
create database company;
-
在此数据库中进行操作
1. not null 约束
-
在
create table
时添加约束create table emp_null( id int not null, name varchar(15) not null, phone varchar(25), salary decimal(10, 2) );
-
在
alter table
时添加约束alter table emp_nill modify phone varchar(25) not null;
-
删除约束(即可以为空)
alter table emp_null modify phone varchar(25) null;
2. unique 约束
-
在
create table
时添加约束create table emp_unique( id int unique, # 列级约束 name varchar(15) , phone varchar(25), salary decimal(10, 2), constraint unique_phone unique(phone) #表级约束 ); # 列级约束:是对某一特定列的约束 # 表级约束:用于对多个列一起的约束 # 在创建唯一约束的时候,如果不给唯一约束命名,就默认和列名相同 # 可以向声明为 unique 的字段上添加 null 值,而且可以多次添加 null
-
在
alter table
时添加约束# 添加表级约束 alter table emp_unique add constraint unique_sal unique(salary); # 添加列级约束 alter table emp_unique modify name varchar(15) unique;
-
复合的约束
create table user( id int, name varchar(15), password varchar(25), constraint uk_name_pwd unique(`name`, `password`) );
-
删除约束
# 删除唯一约束只能通过删除唯一索引的方式删除 # 删除时需要指定唯一索引名,唯一索引名和唯一约束名一样 # 如果创建唯一约束时未指定名称,如果是单列,默认和列名相同 # 如果是组合列,默认和第一个的列名相同 alter table emp_unique drop index id;
3. primary key 约束
-
在
create table
时添加约束create table emp_pri( id int primary key, name varchar(20), salary decimal(10, 2), phone varchar(25) ); # 表级约束 constraint emp_id primary key(id) # 复合主键约束:多列组合的复合主键约束,那么这些列都不允许为空值,并且组合的值不允许重复 create table emp_pri1( id int, name varchar(20), password varchar(25), primary key (name, password) );
-
在
alter table
时添加约束create table emp_pri2( id int, name varchar(20), password varchar(25) ); alter table emp_pri2 add primary key (id);
-
删除主键约束
alter table emp_pri2 drop primary key;
4. foreign key 约束
-
创建父表:表中必须有主键约束或唯一值约束
create table dept( id int primary key, name varchar(20), phone varchar(25) );
-
在
create table
时添加约束create table fk_emp( id int, name varchar(15), dept_id int, # 表级约束 constraint fk_id foreign key (id) references dept(id) );
-
在
alter table
时添加约束alter table fk_emp1 add constraint fk_emp1_k foreign key(id) references dept(id);
-
删除外键约束
# 首先,删除外键约束 alter table fk_emp1 drop foreign key fk_emp1_k ; # 然后,手动删除外键约束对应的普通索引 show index from fk_emp1; alter table cs.emp1 drop index fk_emp1_k;
5. check 约束
-
mysql 5.7 不支持 check 约束,8.0 支持 check 约束。
-
create table emp_check( id int, name varchar(15), salary decimal(10, 2) check(salary > 2000) );
6.其他字段属性介绍
-
auto_increment
:- 添加数据时,该字段不要给值。
- 实际上会自动的往上添加指定的字段的数值。
-
default
:-
设置默认值约束,具体的语法格式如下
-
<字段名> <数据类型> default <默认值>;
-
翻滚的时代浪潮中 曾有多少灵魂抗争。 ——刺猬乐队《赤子呓语一生梦》