Mysql-表关系

表关系分为三种:一对一,一对多,多对多

一对多:一个学院对应多个学生,而一个学生只对应一个学院  

--  这儿classroom 是代表的学院。

-- 一对多 - A表的一条记录 对应 B 表多条记录,B表一条记录 只能对应 A表一条记录
-- 一个classroom对应多个student
-- 创建主表
create table if not exists classroom(
    id int primary key auto_increment,
    name varchar(20)
);
-- 创建子表
create table student(
    id int primary key auto_increment,
    name varchar(10),
    cls_id int,
    constraint `idx_cls_id` foreign key(cls_id) references classroom(id)
);

insert into classroom(name) values('Python学院'),('Web学院'),('Java学院');

insert into student(name,cls_id) values('Which',1);
insert into student(name,cls_id) values('Tuple',1);
insert into student(name,cls_id) values('Tom',3);
insert into student(name,cls_id) values('Tim',2);

-- select * from student;
+----+-------+--------+
| id | name  | cls_id |
+----+-------+--------+
|  1 | Which |      1 |
|  2 | Tuple  |      1  |
|  3 | Tom    |      3  |
|  4 | Tim     |      2  |
+----+-------+--------+

一对一:一个学生对应一个地址,一个地址也对应一个学生

-- 一对一 - A表的一条记录一定只能对应B表一条记录,B表的一条记录一定只能对应A表一条记录

-- 创建学生的地址表 学生和地址一对一关系
create table stu_address(
    id int primary key auto_increment,
    address varchar(10),
    constraint `idx_adrs_id` foreign key(id) references student(id)
);

insert into stu_address(address) values('地球'),('月球'),('Earth'),('Moon');
--在插入第五六条数据会失败,应为上表student只有4个学生,id最多为4
insert into stu_address(address) values('Earth'),('Moon');

-- select * from stu_address;
+----+---------+
| id | address |
+----+---------+
|  1 | 地球    |
|  2 | 月球    |
|  3 | Earth   |
|  4 | Moon    |
+----+---------+

多对多:老师对应多个学生,学生也可以对应多个老师

-- 创建老师表
create table teacher(
    id int primary key auto_increment,
    name char(12) not null

);
insert into teacher(name) values('陈老师'),('郭老师'),('范老师'),('夏老师');

-- 创建老师学生中间表
create table stu_teacher(
    st_id int,
    te_id int,
    primary key(st_id,te_id),
    constraint `idx_st_id` foreign key(st_id) references student(id),
    constraint `idx_te_id` foreign key(te_id) references teacher(id)
);

insert into stu_teacher values(1,1),(1,2),(2,1),(1,3),(3,1);
-- select * from stu_teacher;
+-------+-------+
| st_id | te_id |
+-------+-------+
|     1 |     1 |
|     2 |     1 |
|     3 |     1 |
|     1 |     2 |
|     1 |     3 |
+-------+-------+
原文地址:https://www.cnblogs.com/tangpg/p/8126024.html