第五课 基础篇_多表查询
一.多表关系
项目开发中,在进行数据库表结构设计时,会根据业务要求及业务模块之间的关系,分析并设计表结构,由于业务之间相互关联,所以各个表结构之间也存在着各种联系,基本分三种:
1.一对多(多对一)
案例:部分与员工的关系
关系:一个对门对应多个员工,一个员工对应一个部门
实现:在多的一方建立外键,指向一的一方的主键
2.多对多
案例:学生与课程的关系
关系:一个学生可以选多门课程,移门课程也可以供多个学生选择
实现:建立第三张中间表,中间表至少包含两个外键,分别关联两方的主键
①案例
-- 多表关系
-- 多对多
-- 1.创建学生表
create table student(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '姓名',
no varchar(10) comment '学号'
)comment '学生表';
insert into student values
(null,'迪丽热巴',2000100101),
(null,'李沁',2000100102),
(null,'韩国欧巴',2000100103),
(null,'关晓彤',2000100104);
-- 2.创建课程表
create table course(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '课程名称'
)comment '课程表';
insert into course values
(null,'Java'),
(null,'MySQL'),
(null,'Cocos'),
(null,'Html');
-- 3.创建中间表
create table student_course(
id int auto_increment comment '主键' primary key,
studentid int not null comment '学生ID',
courseid int not null comment '课程ID',
constraint fk_courseid foreign key (courseid) references course(id),
constraint fk_studentid foreign key (studentid) references student(id)
)comment '学生课程中间表';
insert into student_course values
(null,1,1),
(null,1,2),
(null,1,3),
(null,2,2),
(null,2,3),
(null,3,4);
②图形化查看表关系
右键点击中间表student_course→Diagrams→Show Visualzation
3.一对一
案例:用于与用户详情的关系
关系:一对一关系,多用与单表拆分,将一张表的基础字段放在一张表中,其他香型字段放在另一张表中,以提升操作小绿绿
实现:在任意乙方加入外键,关联另外一方的主键,并设置外键为唯一的(UNIQUE)
①案例
--多表关系
--一对一
--1.创建用户基本信息表
create table tb_user(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '姓名',
age int comment '年龄',
gender char(1) comment '1:男,2:女