一、概述
1.概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据。
2.目的:保证数据库中数据的正确、有效性和完整性。
3.分类:
注意:约束是作用于表中字段上的,可以在创建表/修改表的时候添加约束。
二、约束演示
create table user(
id int primary key auto_increment comment 'ID唯一标识',
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 '用户表';
三、外键约束
概念:外键用来让两张表的数据之间建立连接,从而保证数据的一致性和完整性。
注意:目前上述的两张表,在数据库层面,并未建立外键关联,所以是无法保证数据的一致性和完整性的。
添加外键
-- 添加外键
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);
-- 删除外键
alter table emp drop foreign key fk_emp_dept_id;
删除/更新行为
-- 外键的删除和更新行为
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade ;
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update set null on delete set null ;
四、小结