MySQL基础知识学习——约束、实例(三)

文章目录

概述

约束是作用于表中字段上的规则,用于限制存储在表中的数据,目的是保证数据库中数据的正确性、有效性和完整性。

约束

约束 作用
not null 非空约束,指定某列不为空
unique 唯一约束,指定某列和几列组合的数据不能重复
primary key 主键约束,指定某列的数据不能重复、唯一
foreign key 外键,指定该列记录属于主表中的一条记录,参照另一条数据
check 检查,指定一个表达式,用于检验指定数据
  1. 创建部门表
create table dbApartment(
db_id int primary key auto_increment,name varchar(10) not null unique
)comment '部门表';

insert into dbApartment(name)values('研发部','秘书部','销售部','董事')
  1. 创建人员表与数据约束
    其中部门信息为对应的部门表id
create table emp(
empid int primary key auto_increment comment '主键',
username varchar(10) unique not null comment '用户名',
age int check (age<120&& age>18) comment '年龄',
db_id int defalt '1' comment '部门id',
gender varchar(1) comment '性别'
) comment '员工表';
  1. 创建两表约束
    防止人员表中部门id为无效id、不存在的id,需要跟部门表建立约束——创建外键
    其中外键的名称必须再整个数据库的外键中唯一
alter table emp add fk_emp_dp_id foreign key (db_id ) references dbApartment(db_id );

4.约束与删除

部门表成为主表,人员表成为引用表; 删除约束必须先删除从表的引用,才能删除主表信息, 或者删掉约束

//删除约束
alter table emp drop foreign key fk_emp_dp_id;
delete from dbApartment where db_id =1;

配置主表与从表的级联更新和删除

  • 配置后可以删除主表数据,但是关联的从表信息也会删除
alter table emp add constraint fk_emp_dp_id foreign key (db_id ) references dbApartment(db_id ) on update cascade on delete cascade;
  • 配置后可以删除主表数据,关联的从表信息为null
alter table emp add constraint fk_emp_dp_id foreign key (db_id ) references dbApartment(db_id ) on update set null on delete set null;

猜你喜欢

转载自blog.csdn.net/weixin_45496521/article/details/128981128