day 7-15 表与表之间的关系

一. 前言

  表与 表之间有3种对应关系,分别是:

  多对一:一张表中的一个字段中的多个值对应另外一张表中的一个字段值.(多个学生,可以学习同一门课程)

  多对多;一张表中的一个字段值对应另外一张表中的多个字段值(一个作者可以写多本书籍,一本书也可以由多个作者联合编著)

  一对一:一张表中一个字段值对应另外一个张表的一个字段值(一个用户名对应一个博客园的地址)

确认关系的方法:
表1 foreign key 表2 则表1的多条记录对应表2的一条记录,即多对一 利用foreign key的原理我们可以制作两张表的多对多,一对一关系 多对多: 表1的多条记录可以对应表2的一条记录 表2的多条记录也可以对应表1的一条记录 一对一: 表1的一条记录唯一对应表2的一条记录,反之亦然 分析时,我们先从按照上面的基本原理去套,然后再翻译成真实的意义,就很好理解了

 一对一

 1 #先建立被关联的表
 2 
 3 create table user(id int primary key auto_increment,name char(15));
 4 #插入用户数据
 5 insert into user(name) values
 6     ("jack"),
 7     ("chen"),
 8     ("wang"),
 9     ("yaya");
10 
11 
12 #再创建关联表
13 create table blogs(id int primary key auto_increment,address varchar(50),
14 uid int not null unique,foreign key (uid) references user(id));
15 #插入数据
16 insert into blogs(address,uid) values
17     ("www.cnblogs.com/jack",1),
18     ("www.cnblogs.com/chen",2),
19     ("www.cnblogs.com/yaya",4),
20     ("www.cnblogs.com/wang",3);
一对一关系

多对一:

 1 多对一关系:
 2 1.建立被关联表
 3 create  table courses(id int primary key auto_increment,name char(10));
 4 insert into courses(name) values 
 5     ("英语"),
 6     ("语文"),
 7     ("数学");
 8 
 9 2.建立关联表
10 
11 create table students(id int primary key auto_increment,name char(10),course_id int,foreign key (course_id) references courses(id));
12 insert into  students(name,course_id) values
13     ("jack",1),
14     ("chen",1),
15     ("yaya",3),
16     ("wang",3),
17     ("lilei",2);
18     
19 select * from students;
20 +----+-------+-----------+
21 | id | name  | course_id |
22 +----+-------+-----------+
23 |  1 | jack  |         1 |
24 |  2 | chen |         1 |
25 |  3 | yaya |         3 |
26 |  4 | wang|         3 |
27 |  5 | lilei   |         2 |
28 +----+-------+-----------+
29 
30 select * from courses;
31 +----+--------+
32 | id | name   |
33 +----+--------+
34 |  1 | 英语   |
35 |  2 | 语文   |
36 |  3 | 数学   |
37 +----+--------+
多对一

多对多关系

 1 #多对多关系
 2 #1.创建被关联表
 3 create table author1 (id int primary key auto_increment,name char(10));
 4 insert into author1 (name) values
 5     ("jack"),
 6     ("chen"),
 7     ("wang"),
 8     ("lili"),
 9     ("lucy"),
10     ("lilei");
11 
12 
13 
14 create table book1(id int primary key auto_increment,name char(6));
15 insert into book1(name) values
16     ("python入门"),
17     ("linux精通"),
18     ("go实战");
19 
20     
21 #2.创建关联表,book_id和author_id联合唯一,避免出现重复的现象
22 
23 create table book2author1(id int primary key auto_increment,book_id int not null ,author_id int not null, unique(book_id,author_id),
24 foreign key(book_id) references book1(id) on delete cascade on update cascade,
25 foreign key(author_id) references author1(id) on delete cascade on update cascade);
26 
27 
28 insert into book2author1(book_id,author_id)values
29     (1,1),
30     (1,5),
31     (2,4),
32     (2,6),
33     (3,2),
34     (3,3);
多对多关系
原文地址:https://www.cnblogs.com/lovepy3/p/9323629.html