第五课 基础篇_多表查询

第五课 基础篇_多表查询

一.多表关系

项目开发中,在进行数据库表结构设计时,会根据业务要求及业务模块之间的关系,分析并设计表结构,由于业务之间相互关联,所以各个表结构之间也存在着各种联系,基本分三种:

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:女
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值