如何找出两张表之间的关系
分析步骤:
#1、先站在左表的角度去找
是否左表的多条记录可以对应右表的一条记录,如果是,则证明左表的一个字段foreign key 右表一个字段(通常是id)
#2、再站在右表的角度去找
是否右表的多条记录可以对应左表的一条记录,如果是,则证明右表的一个字段foreign key 左表一个字段(通常是id)
#3、总结:
#多对一:
如果只有步骤1成立,则是左表多对一右表
如果只有步骤2成立,则是右表多对一左表
#多对多
如果步骤1和2同时成立,则证明这两张表时一个双向的多对一,即多对多,需要定义一个这两张表的关系表来专门存放二者的关系
#一对一:
如果1和2都不成立,而是左表的一条记录唯一对应右表的一条记录,反之亦然。这种情况很简单,就是在左表foreign key右表的基础上,将左表的外键字段设置成unique即可
建立表之间的关系
#一对多或称为多对一
三张表:出版社,作者信息,书
一对多(或多对一):一个出版社可以出版多本书
关联方式:foreign key
两张表之间的关系
1. 多对一
出版社 书(press_id int,foreign key (preess_id) references press(id))
2. 多对多
3. 一对一
例子
#一对多或称为多对一
三张表:出版社,作者信息,书
一对多(或多对一):一个出版社可以出版多本书
关联方式:foreign key
=====================多对一=====================
create table press(
id int primary key auto_increment,
name varchar(20)
);
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
);
insert into press(name) values
(‘机械工业出版社‘),
(‘人民出版社‘),
(‘南京出版社‘)
;
insert into book(name,press_id) values
(‘计算机基础‘,1),
(‘python入门‘,2),
(‘mysql‘,2),
(‘机械原理‘,3),
(‘十万个为什么‘,2),
(‘社会科学‘,3)
;
# 操作过程
mysql> create table press(
-> id int primary key auto_increment,
-> name varchar(20)
-> );
Query OK, 0 rows affected (0.03 sec)
mysql>
mysql> 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
-> );
Query OK, 0 rows affected (0.03 sec)
mysql> insert into press(name) values
-> (‘机械工业出版社‘),
-> (‘人民出版社‘),
-> (‘南京出版社‘)
-> ;
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql>
mysql> insert into book(name,press_id) values
-> (‘计算机基础‘,1),
-> (‘python入门‘,2),
-> (‘mysql‘,2),
-> (‘机械原理‘,3),
-> (‘十万个为什么‘,2),
-> (‘社会科学‘,3)
-> ;
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> desc press;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
mysql> select * from book;
+----+--------------------+----------+
| id | name | press_id |
+----+--------------------+----------+
| 1 | 计算机基础 | 1 |
| 2 | python入门 | 2 |
| 3 | mysql | 2 |
| 4 | 机械原理 | 3 |
| 5 | 十万个为什么 | 2 |
| 6 | 社会科学 | 3 |
+----+--------------------+----------+
6 rows in set (0.00 sec)
mysql> select * from press;
+----+-----------------------+
| id | name |
+----+-----------------------+
| 1 | 机械工业出版社 |
| 2 | 人民出版社 |
| 3 | 南京出版社 |
+----+-----------------------+
3 rows in set (0.00 sec)