18-MySQL外键

前面学习了数据完整性的概念,而外键就是为了实现表与表之间的引用完整性

一.外键约束-概念

image.png

1.什么是外键?
- 如果一张表中有一个字段引用了另一张表中的主键, 那么这个字段我们就称之为外键
- 例如: 成绩表中的stuid引用了学生表中的id, 那么stuid我们就称之为外键
- 注意点: 成绩表中的stuid引用了学生表中的id, 那么成绩表我们称之为"从表", 学生表称之为主表
By 极客江南

二.外键约束-使用

image.png

image.png

image.png

image.png

image.png

image.png
  • 示例一: 没有约束(默认情况)
    // 学生表
    create table stuinfo(
    id int auto_increment primary key,
    name varchar(20)
    );
    // 成绩表
    create table stugrade(
    id int auto_increment primary key,
    stuid int,
    score float
    );
    #无论有没有某个学生都可以插入数据
    insert into stugrade values(null, 3, 100);
    - 示例二:
    create table stugrade2(
    id int auto_increment primary key,
    stuid int,
    score float,
    \ #告诉MySQL将stuid作为外键, 值是引用stuinfo中的id
    foreign key(stuid) references stuinfo(id)
    );
    insert into stugrade2 values(null, 3, 100); #报错, 因为sutinfo中没有id为3的人
    insert into stuinfo values(null, 'lnj');
    insert into stugrade2 values(null, 3, 100); #报错, 因为sutinfo中没有id为3的人
    insert into stugrade2 values(null, 1, 100);
    delete from stuinfo where id=1; #报错, 因为有其它表引用这这条数据
    外键的特点:
    - 主表中没有对应的数据, 从表不能插入, 因为插入之后数据也不完整
    - 从表引用这主表的数据, 主表不能删除该数据, 因为上次之后数据也不完整
    示例二:
    添加外键的第二种方式:
    create table stugrade3(
    id int auto_increment primary key,
    stuid int,
    score float
    );
    #通过修改表的方式添加外键
    alter table stugrade3 add foreign key(stuid) references stuinfo(id);
    示例三:
    查看外键
    show create table stugrade3\G;
    删除外键
    alter table stugrade3 drop foreign key stugrade3_ibfk_1;
    By 极客江南

三.外键模式-概念

image.png

外键相关的操作
- 严格模式(默认)
+ 主要不存在对应的数据, 从表不允许插入
+ 从表引用着主表的数据, 主表不能删除
+ 从表引用着主表的数据, 主表不能修改
- 置空操作
+ 如果主表中的数据被删除了, 从表中对应的字段变为null, 我们就称之为置空操作
+ 流入: 主表中id为1的人被删除了, 那么从表中的stuid变为null
- 级联操作
+ 如果主表发生了变化, 从表也跟着变化, 我们就称之为级联操作
+ 例如: 主表中'lnj'的id从1变为3, 那么从表中的stuid也从1变为3
By 极客江南

四.外键模式-使用

image.png

image.png
  • 格式:
    foreign key(字段) references 主表名(主表主键)[主表删除的动作][主表更新的动作]
    示例一:
    create table stugrade(
    id int auto_increment primary key,
    stuid int,
    score float,
    \ #注意点: 一般在企业开发中都是删除就清空, 更新就随着更新
    foreign key(stuid) references stuinfo(id) on delete set null on update cascade
    );
    insert into stugrade values(null, 1, 100);
    update stuinfo set id=666 where id=1;
    delete from stuinfo where id=666;
    By 极客江南

你可能感兴趣的:(18-MySQL外键)