表与表之间的关系
分析步骤
分析步骤:
1. 先站在左表的角度分析:
左表的多条记录是否可以对应右表的一条记录,如果是,则需要在左表新建一个foreign key 字段关联右表的一个唯一字段(通常是id)
2. 再站在右表的角度分析:
右表的多条记录是否可以对应左表的一条记录,如果是,则需要在右表新建一个foreign key 字段关联左表的一个唯一字段(通常是id)
一对多 or 多对一
- 如果只有步骤1成立,则表明是左表多对一右表
- 如果只有步骤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
);