首页 > 数据库 >MySQL的多表查询

MySQL的多表查询

时间:2023-01-16 11:56:36浏览次数:40  
标签:comment 多表 查询 MySQL department null id select

多表关系

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

  • 一对多(多对一)
  • 多对多
  • 一对一

一对多

  • 案例: 部门与员工的关系
  • 关系: 一个部门对应多个员工,一个员工对应一个部门
  • 实现: 在多的一方建立外键,指向一的一方的主键
    image
create table department
(
    id   int auto_increment comment 'ID' primary key,
    name varchar(50) not null comment '部门名称'
) comment '部门表';

INSERT INTO department (id, name)
VALUES (1, '研发部'),
       (2, '市场部');

create table employee
(
    id            int auto_increment comment 'ID' primary key,
    name          varchar(50) not null comment '姓名',
    entrydate     date comment '入职时间',
    department_id int comment '部门ID'
) comment '员工表';
insert into employee (id, name, entrydate, department_id)
values (1, '张三', '2023-01-05', 1),
       (2, '李四', '2023-01-06', 2),
       (3, '王五', '2023-01-07', 2),
       (4, '赵六', '2023-01-08', 2);

alter table employee add constraint fk_employee_department_id foreign key (department_id) references department(id);

多对多

  • 案例: 学生与课程的关系
  • 关系: 一个学生可以选修多门课程,一门课程也可以供多个学生选择
  • 实现: 建立第三张中间表,中间表至少包含两个外键,分别关联两方主键
    image
create table student
(
    id   int auto_increment primary key comment '主键ID',
    name varchar(10) comment '姓名',
    number  varchar(10) comment '学号'
) comment '学生表';
insert into student
values (null, '黛绮丝', '2000100101'),
       (null, '谢逊', '2000100102'),
       (null, '殷天正', '2000100103'),
       (null, '韦一笑', '2000100104');

create table course
(
    id   int auto_increment primary key comment '主键ID',
    name varchar(10) comment '课程名称'
) comment '课程表';
insert into course
values (null, 'Java'),
       (null, 'PHP'),
       (null, 'MySQL'),
       (null, 'Hadoop');

create table student_course
(
    id        int auto_increment comment '主键' primary key,
    student_id int not null comment '学生ID',
    course_id  int not null comment '课程ID',
    constraint fk_course_id foreign key (course_id) references course (id),
    constraint fk_student_id foreign key (student_id) 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);

一对一

  • 案例: 用户与用户详情的关系
  • 关系: 一对一关系,多用于单表拆分,将一张表的基础字段放在一张表中,其他详情字段放在另一张表中,以提升操作效率
  • 实现: 在任意一方加入外键,关联另外一方的主键,并且设置外键为唯一的(UNIQUE)
    image
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: 女',
    phone  char(11) comment '手机号'
) comment '用户基本信息表';

create table tb_user_education
(
    id             int auto_increment primary key comment '主键ID',
    degree         varchar(20) comment '学历',
    major          varchar(50) comment '专业',
    primary_school varchar(50) comment '小学',
    middle_school  varchar(50) comment '中学',
    university     varchar(50) comment '大学',
    user_id        int unique comment '用户ID',
    constraint fk_user_id foreign key (user_id) references tb_user (id)
) comment '用户教育信息表';
insert into tb_user(id, name, age, gender, phone)
values (null, '张三', 45, '1', '18800001111'),
       (null, '李四', 35, '2', '18800002222'),
       (null, '王五', 55, '1', '18800008888'),
       (null, '赵六', 50, '1', '18800009999');

insert into tb_user_education(id, degree, major, primary_school, middle_school,
                              university, user_id)
values (null, '本科', '舞蹈', '静安区第一小学', '静安区第一中学', '北京舞蹈学院', 1),
       (null, '硕士', '表演', '朝阳区第一小学', '朝阳区第一中学', '北京电影学院', 2),
       (null, '本科', '英语', '杭州市第一小学', '杭州市第一中学', '杭州师范大学', 3),
       (null, '本科', '应用数学', '阳泉第一小学', '阳泉区第一中学', '清华大学', 4);

多表查询概述

数据准备

create table department
(
    id   int auto_increment comment 'ID' primary key,
    name varchar(50) not null comment '部门名称'
) comment '部门表';
INSERT INTO department (id, name)
VALUES (1, '研发部'),
       (2, '市场部'),
       (3, '财务部'),
       (4, '销售部'),
       (5, '总经办'),
       (6, '人事部');

create table employee
(
    id            int auto_increment comment 'ID' primary key,
    name          varchar(50) not null comment '姓名',
    age           int comment '年龄',
    job           varchar(20) comment '职位',
    salary        int comment '薪资',
    entrydate     date comment '入职时间',
    managerid     int comment '直属领导ID',
    department_id int comment '部门ID'
) comment '员工表';
alter table employee
    add constraint fk_emp_dept_id foreign key (department_id) references department (id);
INSERT INTO employee (id, name, age, job, salary, entrydate, managerid, department_id)
VALUES (1, '金庸', 66, '总裁', 20000, '2000-01-01', null, 5),
       (2, '张无忌', 20, '项目经理', 12500, '2005-12-05', 1, 1),
       (3, '杨逍', 33, '开发', 8400, '2000-11-03', 2, 1),
       (4, '韦一笑', 48, '开发', 11000, '2002-02-05', 2, 1),
       (5, '常遇春', 43, '开发', 10500, '2004-09-07', 3, 1),
       (6, '小昭', 19, '程序员鼓励师', 6600, '2004-10-12', 2, 1),
       (7, '灭绝', 60, '财务总监', 8500, '2002-09-12', 1, 3),
       (8, '周芷若', 19, '会计', 48000, '2006-06-02', 7, 3),
       (9, '丁敏君', 23, '出纳', 5250, '2009-05-13', 7, 3),
       (10, '赵敏', 20, '市场部总监', 12500, '2004-10-12', 1, 2),
       (11, '鹿杖客', 56, '职员', 3750, '2006-10-03', 10, 2),
       (12, '鹤笔翁', 19, '职员', 3750, '2007-05-09', 10, 2),
       (13, '方东白', 19, '职员', 5500, '2009-02-12', 10, 2),
       (14, '张三丰', 88, '销售总监', 14000, '2004-10-12', 1, 4),
       (15, '俞莲舟', 38, '销售', 4600, '2004-10-12', 14, 4),
       (16, '宋远桥', 40, '销售', 4600, '2004-10-12', 14, 4),
       (17, '陈友谅', 42, null, 2000, '2011-10-12', 1, null);

dept表共6条记录,emp表共17条记录。

分类

  • 连接查询
    • 内连接:相当于查询A、B交集部分数据
    • 外连接:
      • 左外连接:查询左表所有数据,以及两张表交集部分数据
      • 右外连接:查询右表所有数据,以及两张表交集部分数据
    • 自连接:当前表与自身的连接查询,自连接必须使用表别名
  • 子查询

内连接

内连接查询的是两张表交集部分的数据。
内连接的语法分为两种: 隐式内连接、显式内连接。

  • 隐式内连接
select 字段列表 from 表1, 表2 where 条件...;
/*案例:*/
select * from employee e, department d where e.department_id=d.id;
  • 显式内连接
select 字段列表 from 表1 [inner] join 表2 on 连接条件...;
/*案例:*/
select * from employee e inner join department d on e.department_id = d.id;

注意事项:一旦为表起了别名,就不能再使用表名来指定对应的字段了,此时只能够使用别名来指定字段。

外连接

外连接分为两种,分别是:左外连接和右外连接。

  • 左外连接
select 字段列表 from 表1 left [outer] join 表2 on 连接条件...;
/*案例:*/
select * from employee e left outer join department d on e.department_id = d.id;

左外连接相当于查询表1(左表)的所有数据,当然也包含表1和表2交集部分的数据。

  • 右外连接
select 字段列表 from 表1 right [outer] join 表2 on 连接条件...;
/*案例:*/
select * from employee e right outer join department d on e.department_id = d.id;

右外连接相当于查询表2(右表)的所有数据,当然也包含表1和表2交集部分的数据。
注意事项: 左外连接和右外连接是可以相互替换的,只需要调整在连接查询时SQL中,表结构的先后顺序就可以了。而我们在日常开发使用时,更偏向于左外连接。

自连接

自连接查询,顾名思义,就是自己连接自己,也就是把一张表连接查询多次。

select 字段列表 from 表A 别名A join 表A 别名B ON 条件 ...;
/*案例:对于自连接查询,可以是内连接查询,也可以是外连接查询。*/
select a.name,b.name from employee a join employee b on a.managerid = b.id;
select a.name,b.name from employee a left join employee b on a.managerid = b.id;

注意事项:在自连接查询中,必须要为表起别名,要不然我们不清楚所指定的条件、返回的字段,到底是哪一张表的字段。

联合查询

对于union查询,就是把多次查询的结果合并起来,形成一个新的查询结果集。

select 字段列表 from 表A ...
union [all]
select 字段列表 from 表B ....;

注意事项:

  • 对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致。
  • union all 会将全部的数据直接合并在一起,union会对合并之后的数据去重。

子查询

概念:SQL语句中嵌套SELECT语句,称为嵌套查询,又称子查询。

select * from t1 where column1 = ( select column1 from t2 );

子查询外部的语句可以是INSERT / UPDATE / DELETE / SELECT 的任何一个。
分类

  • 根据子查询结果不同,分为:
    • 标量子查询(子查询结果为单个值)
    • 列子查询(子查询结果为一列)
    • 行子查询(子查询结果为一行)
    • 表子查询(子查询结果为多行多列)
  • 根据子查询位置,分为:
    • where之后
    • from之后
    • select之后

标量子查询

子查询返回的结果是单个值(数字、字符串、日期等),最简单的形式,这种子查询称为标量子查询。
常用的操作符:= <> > >= < <=

/*案例:查询 "销售部" 的所有员工信息。*/
select *
from employee e
where e.department_id = (select id from department d where name = '销售部');

/*案例:查询在 "方东白" 入职之后的员工信息。*/
select *
from employee e
where e.entrydate > (select entrydate from employee where name = '方东白');

列子查询

子查询返回的结果是一列(可以是多行),这种子查询称为列子查询。
常用的操作符:in 、not in 、 any 、some 、 all

操作符 描述
in 在指定的集合范围之内,多选一
not in 不在指定的集合范围之内
any 子查询返回列表中,有任意一个满足即可
some 与any等同,使用some的地方都可以使用any
all 子查询返回列表的所有值都必须
/*案例:查询 "销售部" 和 "市场部" 的所有员工信息*/
select *
from employee e
where e.department_id in (select id from department where name = '销售部' or name = '市场部');

/*案例:查询比 销售部 所有人工资都高的员工信息*/
select *
from employee e2
where e2.salary > all
      (select salary from employee e where e.department_id = (select id from department where name = '销售部'));

/*案例:查询比研发部其中任意一人工资高的员工信息*/
select *
from employee e2
where e2.salary > any
      (select salary from employee e where e.department_id = (select id from department where name = '研发部'));

行子查询

子查询返回的结果是一行(可以是多列),这种子查询称为行子查询。
常用的操作符:= 、<> 、in 、not in

/*案例:查询与 "张无忌" 的薪资及直属领导相同的员工信息*/
select *
from employee
where (salary, managerid) = (select salary, managerid from employee where name = '张无忌');

表子查询

子查询返回的结果是多行多列,这种子查询称为表子查询。
常用的操作符:in

/*案例:查询与 "鹿杖客" , "宋远桥" 的职位和薪资相同的员工信息*/
select *
from employee
where (job, salary) in (select job, salary from employee where name ='鹿杖客'or name = '宋远桥');

/*案例:查询入职日期是 "2006-01-01" 之后的员工信息 , 及其部门信息*/
select e.*, d.*
from (select * from employee where entrydate > '2006-01-01') e
left join department d on e.department_id = d.id;

标签:comment,多表,查询,MySQL,department,null,id,select
From: https://www.cnblogs.com/yellow-mokey/p/17054846.html

相关文章

  • 查询指定地址所属的街道办事处
    https://www.youbianku.com/如何快速查询某个地址所属街道办事处......
  • ubuntu查询硬盘使用情况及文件或文件夹大小命令
    使用ubuntu系统时,经常要查系统剩余空间,以及目录大小这是常用指令:磁盘空间使用情况df-h当前目录所有文件及文件夹大小du--max-depth=1-h的简化版本du-hd1查看单个文件......
  • Mysql备份数据库结构和数据的脚本
    echo取日期、时间变量值setyy=%date:~0,4%setmm=%date:~5,2%setdd=%date:~8,2%if/i%time:~0,2%lss10sethh=0%time:~1,1%if/i%time:~0,2%geq10set......
  • MySQL中的any_value()函数
    在工作中第第一次接触到any_value()函数,自己去了解这个函数的作用。简单来说,在MySQL5.7之后,如果有使用groupby对字段A、B……分组,那么select后面的查询项必须包含group......
  • Mysql:索引失效的常见场景
    索引失效的常见场景不符合最佳左前缀原则比如说现在创建一个联合索引:index_union(name,age),然后你的select语句是这样的select*fromuserwhereage=18此情况下......
  • mysql mgr demo
    dockercompose配置services:db:container_name:mgr-db-0image:mysql:8.0restart:alwaysenvironment:MYSQL_ROOT_PASSWORD:'123456'......
  • 在尝试加载程序集 ID 65536 时 Microsoft .NET Framework 出错。服务器可能资源不足,或
    SqlServer 函数中执行的程序集但用户的权限不够,后DBA使用sa 账号设置了就对了网上找到的解决方法:这数据库是从其他数据库还原到本地数据库的,不少网友说在还原数据库之......
  • Mysql:explain
    explainmysql提供了一种方式,目的是为了让我们知道sql的执行顺序、索引使用情况、执行效率的情况tabletable是展示执行计划过程中,会使用到的表。执行explain出现的每条......
  • 【学习日志】MySQL分表与索引的关系
    什么情况下需要分表呢?分表又能解决什么问题呢?一般情况下分表的直接原因是数据量太大了,比如一张表一共只有1w条数据,确实没必要分表。为什么数据量大了就需要分表呢?首先得看......
  • MySQL判断数据是不是存在的方法
        在mysql中,可以利用count()函数判断数据是否存在,该函数的作用就是用来统计表中记录数据,语法为“selectCOUNT(字段值)as字段名from表名where字段条件;”,......