MYSQL表关系

表关系

一、外键--Foreign Key

​   作用:约束当前表的某列值必须取自于另一张表的主键列值

​   外键所在的列称之为“外键列”

​   外键所在的表称之为“外键表”或“子表”

​   被外键列所引用的表称之为“主表”或“主键表”

  语法:

  1.创建表的同时指定外键

  create table xxx(

  字段 类型,

  ...,

  constraint 外键名 foreign key(字段)

  references 主键表(主键列)

  )

 

-- 创建course表:id,cname,cduration
 create  table course(
    id int primary key auto_increment,
    cname varchar(30) not null,
    cduration int not null
 )
-- 创建teacher表:id,name,age,gender,hobby,course
-- course_id是外键,引用自course表的主键id
 create table teacher(
    id int primary key auto_increment,
    name varchar(30) not null,
    age int not null,
    gender varchar(2) not null,
    hobby varchar(50) not null,
    course_id int,
    -- 外键约束
    constraint fk_course_teacher
    foreign key(course_id) -- 设置外键
    references course(id) -- 参照主键(参照course的id值)参照谁就写谁
 )

​   2.对已有表增加外键

​   alter table 表名

​   add constraint 外键名

​   foreign key(字段)

​   references 主键表(主键)

-- 创建student表:id,name,age,gender,school,class_id,major_id
    create table student(
    id int primary key auto_increment,
    name varchar(30) not null,
    age int not null,
    gender varchar(2) not null,
    school varchar(100) not null,
    class_id int not null,
    major_id int not null
 );
-- 创建classinfo表:id,classname,status
    create table classinfo(
    id int primary key auto_increment,
    classname varchar(30) not null,
    status varchar(2) not null
    );
-- 更新student表结构,增加外键在class_id,引用子classinfo表的主键id
    alter table student
    add constraint fk_class_student
    foreign key(class)
    references classinfo(id)

  3.删除外键

  alter table 表名 drop foreign key 外键名;

  4.查看外键名

  show create table 表名;

二、级联操作

​ 1.语法:

  alter table 表名

  add constraint 外键名

  foreign key(字段)

  references 主键表(主键)

  on delete 级联操作

  on update 级联操作

-- 为score表中的stu_id增加外键,并设置级联操作
    alter table score
    add constraint fk_student_score
    foreign key(stu_id)
    references student(id)
    on delete cascade
    on update cascade

​ 2.级联操作取值

  (1)cascade

  数据级联删除、更新(主表有啥动作,子表跟着有啥动作)

  (2)restrict(默认)

  子表中有关联数据,那么主表中就不允许做删除、更新。

  (3)set null

  主表删除数据时子表中的相关数据会设置为null

 

 

 

posted @ 2019-07-09 23:12  maplethefox  阅读(341)  评论(0编辑  收藏  举报