MySQL数据库之主表与从表

数据完整性

数据完整性包括

  • 实体完整性

    • 主键约束
    • 唯一约束
    • 标识列
  • 域完整性

    • 数据类型约束
    • 非空约束
    • 默认值约束
  • 引用完整性

    • 外键约束
  • 自定义完整性

    • 存储过程
    • 触发器

主表和从表

  • 主表与从表的关系
    • 主表中没有的记录,从表不允许插入
    • 从表中有的记录,主表中不允许删除
      1. 删除主表前,先删从表

外键

  • 外键
    • 从表中的公共字段
    • 只有innodb才能支持外键
    • 公共字段的名字可以不一样,但是数据类型要一样
    • 通过关键字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`

三种外键操作

  • 严格限制

    • 参见主表和从表
  • 置空操作(set null)

    • 如果主表记录删除,或关联字段更新,则从表外键字段被设置为null
  • 级联操作(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;
posted @ 2020-12-15 12:05  wing1377  阅读(1339)  评论(0编辑  收藏  举报