MySQL学习之表与表之间的关系

表与表之间的关系

分析步骤

分析步骤:
1. 先站在左表的角度分析:
    左表的多条记录是否可以对应右表的一条记录,如果是,则需要在左表新建一个foreign key 字段关联右表的一个唯一字段(通常是id)
2. 再站在右表的角度分析:
    右表的多条记录是否可以对应左表的一条记录,如果是,则需要在右表新建一个foreign key 字段关联左表的一个唯一字段(通常是id)

一对多 or 多对一

  1. 如果只有步骤1成立,则表明是左表多对一右表
  2. 如果只有步骤2成立,则表明是右表多对一左表
    关联方式: foreign key 即可
create table book(
        id int primary key auto_increment,
        name varchar(20),
        press_id int not null,
        foreign key(press_id) references press(id)
        on delete cascade
        on update cascade
);

总结

在条件为 左表的多条记录可以对应右表的一条记录,反之不成立的情况下,则表明是左表多对一右表,需要在左表新建一个foreign key字段关联右表的一个唯一字段。
上述将条件反过来的话,则表明是右表多对一左表,需要在右表新建一个foreign key字段关联左表的一个唯一字段

多对多

如果步骤1和2同时成立,则证明这两张表示一个双向的多对一,
即多对多,需要定义一个存放二者关系的关系表
关联方式: foreign key + 一张新的表

# 新的表:
create table author2book(
        id integer not null unique auto_increment,
        author_id int not null,
        book_id int not null,
        constraint fk_author foreign key(author_id)
        references author(id)
        on delete cascade
        on update cascade,
        constraint fk_book foreign key(book_id)
        references book(id)
        on delete cascade
        on update cascade,
        primary key(author_id, book_id)
);

总结

左表的多条记录可以对应右表的一条记录, 右表的多条记录也可以对应左表的一条记录,
则证明这两张表表示的是一个双向的多对一, 即多对多, 需要定义一张新的表来存放他们二者之间的关系

一对一

如果1和2都不成立,而是左表的一条记录唯一对应右表的一条记录,反之亦然。
这种情况很简单,就是在左表foreign key右表的基础上,将左表的外键字段设置成unique即可

关联方式: foreign key + unique

create table student(
        id int primary key auto_increment,
        class_name varchar(20) not null,
        customer_id int,
        unique(customer_id),
        constraint foreign key(customer_id)
        references customer(id)
        on delete cascade
        on update cascade
);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值