数据库MySQL-数据完整性

1.5 数据完整性

1.5.1 数据完整性包括

1、实体完整性

1、主键约束
2、唯一约束
3、标识列

2、 域完整性

1、数据类型约束
2、非空约束
3、默认值约束

3、 引用完整性

外键约束

4、 自定义完整性

1、存储过程
2、触发器

1.5.2 主表和从表

  1. 主表中没有的记录,从表不允许插入
  2. 从表中有的记录,主表中不允许删除
  3. 删除主表前,先删子表

1.5.3 外键(foreign key)

外键:从表中的公共字段

-- 创建表的时候添加外键
drop table if exists stuinfo;
create table stuinfo(
       id tinyint primary key,
       name varchar(20)
)engine=innodb;

drop table if exists stuscore;
create table stuscore(
       sid tinyint primary key,
       score tinyint unsigned,
       foreign key(sid) references stuinfo(id)   -- 创建外键
)engine=innodb;

-- 通过修改表的时候添加外键
语法:alter table 从表 add foreign key(公共字段) references 主表(公共字段)

drop table if exists stuinfo;
create table stuinfo(
       id tinyint primary key,
       name varchar(20)
)engine=innodb;

drop table if exists stuscore;
create table stuscore(
       sid tinyint primary key,
       score tinyint unsigned
)engine=innodb;

alter table stuscore add foreign key (sid) references stuinfo(id)

删除外键

通过外键的名字删除外键

在这里插入图片描述

-- 删除外键
mysql> alter table stuscore drop foreign key `stuscore_ibfk_1`;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

小结:

1、只有innodb才能支持外键
2、公共字段的名字可以不一样,但是数据类型要一样

1.5.4 三种外键操作

1、 严格限制(参见主表和从表)

2、 置空操作(set null):如果主表记录删除,或关联字段更新,则从表外键字段被设置为null。

3、 级联操作(cascade):如果主表记录删除,则从表记录也被删除。主表更新,从表外键字段也更新。

语法:foreign key (外键字段) references 主表名 (关联字段) [主表记录删除时的动作] [主表记录更新时的动作]。

一般说删除时置空,更新时级联。

drop table if exists stuinfo;
create table stuinfo(
       id tinyint primary key comment '学号,主键',
       name varchar(20) comment '姓名'
)engine=innodb;

drop table if exists stuscore;
create table stuscore(
       id int auto_increment primary key comment '主键',
       sid tinyint comment '学号,外键',
       score tinyint unsigned comment '成绩',
       foreign key(sid) references stuinfo(id) on delete set null on update cascade
)engine=innodb;

小结:

置空、级联操作中外键不能是从表的主键
发布了1862 篇原创文章 · 获赞 1983 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/105134996