MySQL高级之关系

1、关系

建立成绩表scores,结构以下ui

  • id
  • 学生
  • 科目
  • 成绩

思考:学生列应该存什么信息呢?spa

答:学生列的数据不是在这里新建的,而应该从学生表引用过来,关系也是一条数据;根据范式要求应该存储学生的编号,而不是学生的姓名等其它信息同理,科目表也是关系列,引用科目表中的数据rest

 

建立表的语句以下code

create table scores(
  id int primary key auto_increment,
  stuid int,
  subid int,
  score decimal(5,2)
);

2、外键

思考:怎么保证关系列数据的有效性呢?任何整数均可以吗?blog

答:必须是学生表中id列存在的数据,能够经过外键约束进行数据的有效性验证为stuid添加外键约束ci

alter table scores add constraint stu_sco foreign key(stuid) references students(id);

此时插入或者修改数据时,若是stuid的值在students表中不存在则会报错rem

在建立表时能够直接建立约束io

create table scores(
    id int primary key auto_increment,
    stuid int,
    subid int,
    score decimal(5,2),
    foreign key(stuid) references students(id),
    foreign key(subid) references subjects(id)
);

3、外键的级联操做

在删除students表的数据时,若是这个id值在scores中已经存在,则会抛异常table

推荐使用逻辑删除,还能够解决这个问题class

能够建立表时指定级联操做,也能够在建立表后再修改外键的级联操做

语法:

alter table scores add constraint stu_sco foreign key(stuid) references students(id) on delete cascade;

级联操做的类型包括:

  • restrict(限制):默认值,抛异常
  • cascade(级联):若是主表的记录删掉,则从表中相关联的记录都将被删除
  • set null:将外键设置为空
  • no action:什么都不作
相关文章
相关标签/搜索