MySQL进阶

MySQL进阶

取自黑马程序员,仅供学习。

在MySQL基础内容中,我们讲解了:

  • 使用DDL语句来操作数据库以及表结构(数据库设计)
  • 使用DML语句来完成数据库中数据的增、删、改操作(数据库操作)

我们今天还是继续学习数据库操作方面的内容:查询(DQL语句)。

查询操作我们分为两部分学习:

  • DQL语句-单表操作
  • DQL语句-多表操作

1. 数据库操作-DQL

1.1 介绍

DQL英文全称是Data Query Language(数据查询语言),用来查询数据库表中的记录。

查询关键字:SELECT

查询操作是所有SQL语句当中最为常见,也是最为重要的操作。在一个正常的业务系统中,查询操作的使用频次是要远高于增删改操作的。当我们打开某个网站或APP所看到的展示信息,都是通过从数据库中查询得到的,而在这个查询过程中,还会涉及到条件、排序、分页等操作。

image-20220611103943417

1.2 语法

DQL查询语句,语法结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
SELECT
字段列表
FROM
表名列表
WHERE
条件列表
GROUP BY
分组字段列表
HAVING
分组后条件列表
ORDER BY
排序字段列表
LIMIT
分页参数

我们今天会将上面的完整语法拆分为以下几个部分学习:

  • 基本查询(不带任何条件)
  • 条件查询(where)
  • 分组查询(group by)
  • 排序查询(order by)
  • 分页查询(limit)

准备一些测试数据用于查询操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
create database db02; -- 创建数据库
use db02; -- 切换数据库
-- 员工管理(带约束)
create table tb_emp (
id int unsigned primary key auto_increment comment 'ID',
username varchar(20) not null unique comment '用户名',
password varchar(32) default '123456' comment '密码',
name varchar(10) not null comment '姓名',
gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
image varchar(300) comment '图像',
job tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管',
entrydate date comment '入职时间',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '修改时间'
) comment '员工表';

-- 准备测试数据
INSERT INTO tb_emp (id, username, password, name, gender, image, job, entrydate, create_time, update_time) VALUES
(1, 'jinyong', '123456', '金庸', 1, '1.jpg', 4, '2000-01-01', '2022-10-27 16:35:33', '2022-10-27 16:35:35'),
(2, 'zhangwuji', '123456', '张无忌', 1, '2.jpg', 2, '2015-01-01', '2022-10-27 16:35:33', '2022-10-27 16:35:37'),
(3, 'yangxiao', '123456', '杨逍', 1, '3.jpg', 2, '2008-05-01', '2022-10-27 16:35:33', '2022-10-27 16:35:39'),
(4, 'weiyixiao', '123456', '韦一笑', 1, '4.jpg', 2, '2007-01-01', '2022-10-27 16:35:33', '2022-10-27 16:35:41'),
(5, 'changyuchun', '123456', '常遇春', 1, '5.jpg', 2, '2012-12-05', '2022-10-27 16:35:33', '2022-10-27 16:35:43'),
(6, 'xiaozhao', '123456', '小昭', 2, '6.jpg', 3, '2013-09-05', '2022-10-27 16:35:33', '2022-10-27 16:35:45'),
(7, 'jixiaofu', '123456', '纪晓芙', 2, '7.jpg', 1, '2005-08-01', '2022-10-27 16:35:33', '2022-10-27 16:35:47'),
(8, 'zhouzhiruo', '123456', '周芷若', 2, '8.jpg', 1, '2014-11-09', '2022-10-27 16:35:33', '2022-10-27 16:35:49'),
(9, 'dingminjun', '123456', '丁敏君', 2, '9.jpg', 1, '2011-03-11', '2022-10-27 16:35:33', '2022-10-27 16:35:51'),
(10, 'zhaomin', '123456', '赵敏', 2, '10.jpg', 1, '2013-09-05', '2022-10-27 16:35:33', '2022-10-27 16:35:53'),
(11, 'luzhangke', '123456', '鹿杖客', 1, '11.jpg', 2, '2007-02-01', '2022-10-27 16:35:33', '2022-10-27 16:35:55'),
(12, 'hebiweng', '123456', '鹤笔翁', 1, '12.jpg', 2, '2008-08-18', '2022-10-27 16:35:33', '2022-10-27 16:35:57'),
(13, 'fangdongbai', '123456', '方东白', 1, '13.jpg', 1, '2012-11-01', '2022-10-27 16:35:33', '2022-10-27 16:35:59'),
(14, 'zhangsanfeng', '123456', '张三丰', 1, '14.jpg', 2, '2002-08-01', '2022-10-27 16:35:33', '2022-10-27 16:36:01'),
(15, 'yulianzhou', '123456', '俞莲舟', 1, '15.jpg', 2, '2011-05-01', '2022-10-27 16:35:33', '2022-10-27 16:36:03'),
(16, 'songyuanqiao', '123456', '宋远桥', 1, '16.jpg', 2, '2010-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:05'),
(17, 'chenyouliang', '12345678', '陈友谅', 1, '17.jpg', null, '2015-03-21', '2022-10-27 16:35:33', '2022-10-27 16:36:07'),
(18, 'zhang1', '123456', '张一', 1, '2.jpg', 2, '2015-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:09'),
(19, 'zhang2', '123456', '张二', 1, '2.jpg', 2, '2012-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:11'),
(20, 'zhang3', '123456', '张三', 1, '2.jpg', 2, '2018-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:13'),
(21, 'zhang4', '123456', '张四', 1, '2.jpg', 2, '2015-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:15'),
(22, 'zhang5', '123456', '张五', 1, '2.jpg', 2, '2016-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:17'),
(23, 'zhang6', '123456', '张六', 1, '2.jpg', 2, '2012-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:19'),
(24, 'zhang7', '123456', '张七', 1, '2.jpg', 2, '2006-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:21'),
(25, 'zhang8', '123456', '张八', 1, '2.jpg', 2, '2002-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:23'),
(26, 'zhang9', '123456', '张九', 1, '2.jpg', 2, '2011-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:25'),
(27, 'zhang10', '123456', '张十', 1, '2.jpg', 2, '2004-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:27'),
(28, 'zhang11', '123456', '张十一', 1, '2.jpg', 2, '2007-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:29'),
(29, 'zhang12', '123456', '张十二', 1, '2.jpg', 2, '2020-01-01', '2022-10-27 16:35:33', '2022-10-27 16:36:31');

1.3 基本查询

在基本查询的DQL语句中,不带任何的查询条件,语法如下:

  • 查询多个字段

    1
    select 字段1, 字段2, 字段3 from  表名;
  • 查询所有字段(通配符)

    1
    select *  from  表名;
  • 设置别名

    1
    select 字段1 [ as 别名1 ] , 字段2 [ as 别名2 ]  from  表名;
  • 去除重复记录

    1
    select distinct 字段列表 from  表名;

案例1:查询指定字段 name,entrydate并返回

1
select name,entrydate from tb_emp;

image-20221206112810199

案例2:查询返回所有字段

1
select * from tb_emp;

*号代表查询所有字段,在实际开发中尽量少用(不直观、影响效率)

image-20221206113904763

案例3:查询所有员工的 name,entrydate,并起别名(姓名、入职日期)

1
2
3
4
5
6
-- 方式1:
select name AS 姓名, entrydate AS 入职日期 from tb_emp;
-- 方式2: 别名中有特殊字符时,使用''或""包含
select name AS '姓 名', entrydate AS '入职日期' from tb_emp;
-- 方式3:
select name AS "姓名", entrydate AS "入职日期" from tb_emp;

image-20221206114752149

案例4:查询已有的员工关联了哪几种职位(不要重复)

1
select distinct job from tb_emp;

image-20221206115440117

1.4 条件查询

语法:

1
select  字段列表  from   表名   where   条件列表 ; -- 条件列表:意味着可以有多个条件

学习条件查询就是学习条件的构建方式,而在SQL语句当中构造条件的运算符分为两类:

  • 比较运算符
  • 逻辑运算符

常用的比较运算符如下:

比较运算符 功能
> 大于
>= 大于等于
< 小于
<= 小于等于
= 等于
<> 或 != 不等于
between … and … 在某个范围之内(含最小、最大值)
in(…) 在in之后的列表中的值,多选一
like 占位符 模糊匹配(_匹配单个字符, %匹配任意个字符)
is null 是null

常用的逻辑运算符如下:

逻辑运算符 功能
and 或 && 并且 (多个条件同时成立)
or 或 || 或者 (多个条件任意一个成立)
not 或 ! 非 , 不是

案例1:查询 姓名 为 杨逍 的员工

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where name = '杨逍'; -- 字符串使用''或""包含

image-20221206121255784

案例2:查询 id小于等于5 的员工信息

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where id <=5;

image-20221206121523712

案例3:查询 没有分配职位 的员工信息

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where job is null ;

image-20221206121754267

注意:查询为NULL的数据时,不能使用 = null

image-20221206122036970

案例4:查询 有职位 的员工信息

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where job is not null ;

image-20221206122454101

案例5:查询 密码不等于 ‘123456’ 的员工信息

1
2
3
4
5
6
7
8
-- 方式1:
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where password <> '123456';
-- 方式2:
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where password != '123456';

image-20221206122712152

案例6:查询 入职日期 在 ‘2000-01-01’ (包含) 到 ‘2010-01-01’(包含) 之间的员工信息

1
2
3
4
5
6
7
8
-- 方式1:
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where entrydate>='2000-01-01' and entrydate<='2010-01-01';
-- 方式2: between...and
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where entrydate between '2000-01-01' and '2010-01-01';

image-20221206125100857

案例7:查询 入职时间 在 ‘2000-01-01’ (包含) 到 ‘2010-01-01’(包含) 之间 且 性别为女 的员工信息

1
2
3
4
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where entrydate between '2000-01-01' and '2010-01-01'
and gender = 2;

image-20221206125356737

案例8:查询 职位是 2 (讲师), 3 (学工主管), 4 (教研主管) 的员工信息

1
2
3
4
5
6
7
8
-- 方式1:使用or连接多个条件
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where job=2 or job=3 or job=4;
-- 方式2:in关键字
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where job in (2,3,4);

image-20221206141451342

案例9:查询 姓名 为两个字的员工信息

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where name like '__'; # 通配符 "_" 代表任意1个字符

image-20221206141937293

案例10:查询 姓 ‘张’ 的员工信息

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where name like '张%'; # 通配符 "%" 代表任意个字符(0个 ~ 多个)

image-20221206142156154

1.5 聚合函数

之前我们做的查询都是横向查询,就是根据条件一行一行的进行判断,而使用聚合函数查询就是纵向查询,它是对一列的值进行计算,然后返回一个结果值。(将一列数据作为一个整体,进行纵向计算)

语法:

1
select  聚合函数(字段列表)  from  表名 ;

注意 : 聚合函数会忽略空值,对NULL值不作为统计。

常用聚合函数:

函数 功能
count 统计数量
max 最大值
min 最小值
avg 平均值
sum 求和

count :按照列去统计有多少行数据。

  • 在根据指定的列统计的时候,如果这一列中有null的行,该行不会被统计在其中。

sum :计算指定列的数值和,如果不是数值类型,那么计算结果为0

max :计算指定列的最大值

min :计算指定列的最小值

avg :计算指定列的平均值

案例1:统计该企业员工数量

1
2
3
4
5
6
7
8
9
10
# count(字段)
select count(id) from tb_emp;-- 结果:29
select count(job) from tb_emp;-- 结果:28 (聚合函数对NULL值不做计算)

# count(常量)
select count(0) from tb_emp;
select count('A') from tb_emp;

# count(*) 推荐此写法(MySQL底层进行了优化)
select count(*) from tb_emp;

案例2:统计该企业最早入职的员工

1
select min(entrydate) from tb_emp;

image-20221206160145339

案例3:统计该企业最迟入职的员工

1
select max(entrydate) from tb_emp;

image-20221206160307416

案例4:统计该企业员工 ID 的平均值

1
select avg(id) from tb_emp;

image-20221206160416605

案例5:统计该企业员工的 ID 之和

1
select sum(id) from tb_emp;

image-20221206160604073

1.6 分组查询

分组: 按照某一列或者某几列,把相同的数据进行合并输出。

分组其实就是按列进行分类(指定列下相同的数据归为一类),然后可以对分类完的数据进行合并计算。

分组查询通常会使用聚合函数进行计算。

语法:

1
select  字段列表  from  表名  [where 条件]  group by 分组字段名  [having 分组后过滤条件];

案例1:根据性别分组 , 统计男性和女性员工的数量

1
2
3
select gender, count(*)
from tb_emp
group by gender; -- 按照gender字段进行分组(gender字段下相同的数据归为一组)

image-20221206172615000

案例2:查询入职时间在 ‘2015-01-01’ (包含) 以前的员工 , 并对结果根据职位分组 , 获取员工数量大于等于2的职位

1
2
3
4
5
select job, count(*)
from tb_emp
where entrydate <= '2015-01-01' -- 分组前条件
group by job -- 按照job字段分组
having count(*) >= 2; -- 分组后条件

注意事项:

​ • 分组之后,查询的字段一般为聚合函数和分组字段,查询其他字段无任何意义

​ • 执行顺序:where > 聚合函数 > having

where与having区别(面试题)

  • 执行时机不同:where是分组之前进行过滤,不满足where条件,不参与分组;而having是分组之后对结果进行过滤。
  • 判断条件不同:where不能对聚合函数进行判断,而having可以。

1.7 排序查询

排序在日常开发中是非常常见的一个操作,有升序排序,也有降序排序。

语法:

1
2
3
4
5
select  字段列表  
from 表名
[where 条件列表]
[group by 分组字段 ]
order by 字段1 排序方式1 , 字段2 排序方式2 … ;
  • 排序方式:

    • ASC :升序(默认值)

    • DESC:降序

案例1:根据入职时间, 对员工进行升序排序

1
2
3
4
5
6
7
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
order by entrydate ASC; -- 按照entrydate字段下的数据进行升序排序

select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
order by entrydate; -- 默认就是ASC(升序)

image-20221206175720337

注意事项:如果是升序, 可以不指定排序方式ASC

案例2:根据入职时间,对员工进行降序排序

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
order by entrydate DESC; -- 按照entrydate字段下的数据进行降序排序

image-20221206180358367

案例3:根据入职时间对公司的员工进行升序排序,入职时间相同,再按照更新时间进行降序排序

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
order by entrydate ASC , update_time DESC;

image-20221206180824583

注意事项:如果是多字段排序,当第一个字段值相同时,才会根据第二个字段进行排序

1.8 分页查询

分页操作在业务系统开发时,也是非常常见的一个功能,日常我们在网站中看到的各种各样的分页条,后台也都需要借助于数据库的分页操作。

image-20221206183310586

分页查询语法:

1
select  字段列表  from   表名  limit  起始索引, 查询记录数 ;

案例1:从起始索引0开始查询员工数据, 每页展示5条记录

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
limit 0 , 5; -- 从索引0开始,向后取5条记录

image-20221206185257834

案例2:查询 第1页 员工数据, 每页展示5条记录

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
limit 5; -- 如果查询的是第1页数据,起始索引可以省略,直接简写为:limit 条数

image-20221206184957410

案例3:查询 第2页 员工数据, 每页展示5条记录

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
limit 5 , 5; -- 从索引5开始,向后取5条记录

image-20221206184602569

案例4:查询 第3页 员工数据, 每页展示5条记录

1
2
3
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
limit 10 , 5; -- 从索引10开始,向后取5条记录

image-20221206184414356

注意事项:

  1. 起始索引从0开始。 计算公式 : 起始索引 = (查询页码 - 1)* 每页显示记录数

  2. 分页查询是数据库的方言,不同的数据库有不同的实现,MySQL中是LIMIT

  3. 如果查询的是第一页数据,起始索引可以省略,直接简写为 limit 条数

1.9 案例

DQL的基本语法我们学习结束了,接下来我们就运用所掌握的DQL语句的语法来完成两个案例。

1.9.1 案例一

案例:根据需求完成员工管理的条件分页查询

image-20221206212240773

分析:根据输入的条件,查询第1页数据

  1. 在员工管理的列表上方有一些查询条件:员工姓名、员工性别,员工入职时间(开始时间~结束时间)

    • 姓名:张
    • 性别:男
    • 入职时间:2000-01-01 ~ 2015-12-31
  2. 除了查询条件外,在列表的下面还有一个分页条,这就涉及到了分页查询

    • 查询第1页数据(每页显示10条数据)
  3. 基于查询的结果,按照修改时间进行降序排序

结论:条件查询 + 分页查询 + 排序查询

SQL语句代码:

1
2
3
4
5
6
7
8
9
10
11
12
-- 根据输入条件查询第1页数据(每页展示10条记录)
-- 输入条件:
-- 姓名:张 (模糊查询)
-- 性别:男
-- 入职时间:2000-01-01 ~ 2015-12-31
-- 分页: 0 , 10
-- 排序: 修改时间 DESC
select id, username, password, name, gender, image, job, entrydate, create_time, update_time
from tb_emp
where name like '张%' and gender = 1 and entrydate between '2000-01-01' and '2015-12-31'
order by update_time desc
limit 0 , 10;

image-20221206213235786

1.9.2 案例二

案例:根据需求完成员工信息的统计

image-20221206210536118

分析:以上信息统计在开发中也叫图形报表(将统计好的数据以可视化的形式展示出来)

  • 员工性别统计:以饼状图的形式展示出企业男性员人数和女性员工人数
    • 只要查询出男性员工和女性员工各自有多少人就可以了
  • 员工职位统计:以柱状图的形式展示各职位的在岗人数
    • 只要查询出各个职位有多少人就可以了

员工性别统计:

1
2
3
4
-- if(条件表达式, true取值 , false取值)
select if(gender=1,'男性员工','女性员工') AS 性别, count(*) AS 人数
from tb_emp
group by gender;

image-20221206220908397

if(表达式, tvalue, fvalue) :当表达式为true时,取值tvalue;当表达式为false时,取值fvalue

员工职位统计:

1
2
3
4
5
6
7
8
9
10
11
-- case 表达式 when 值1 then 结果1  when 值2  then  结果2 ...  else  result  end
select (case job
when 1 then '班主任'
when 2 then '讲师'
when 3 then '学工主管'
when 4 then '教研主管'
else '未分配职位'
end) AS 职位 ,
count(*) AS 人数
from tb_emp
group by job;

image-20221206221718731

case 表达式 when 值1 then 结果1 [when 值2 then 结果2 …] [else result] end

2. 多表设计

关于单表的操作(单表的设计、单表的增删改查)我们就已经学习完了。接下来我们就要来学习多表的操作,首先来学习多表的设计。

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

  • 一对多(多对一)

  • 多对多

  • 一对一

2.1 一对多

2.1.1 表设计

需求:根据页面原型及需求文档 ,完成部门及员工的表结构设计

  • 员工管理页面原型:(前面已完成tb_emp表结构设计)

  • 部门管理页面原型:

image-20221206224149094

经过上述分析,现已明确的部门表结构:

  • 业务字段 : 部门名称
  • 基础字段 : id(主键)、创建时间、修改时间

部门表 - SQL语句:

1
2
3
4
5
6
7
8
9
10
11
12
# 建议:创建新的数据库(多表设计存放在新数据库下)
create database db03;
use db03;

-- 部门表
create table tb_dept
(
id int unsigned primary key auto_increment comment '主键ID',
name varchar(10) not null unique comment '部门名称',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '修改时间'
) comment '部门表';

部门表创建好之后,我们还需要再修改下员工表。为什么要修改员工表呢?是因为我们之前设计员工表(单表)的时候,并没有考虑员工的归属部门。

image-20221206224642902

员工表:添加归属部门字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
-- 员工表
create table tb_emp
(
id int unsigned primary key auto_increment comment 'ID',
username varchar(20) not null unique comment '用户名',
password varchar(32) default '123456' comment '密码',
name varchar(10) not null comment '姓名',
gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
image varchar(300) comment '图像',
job tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管',
entrydate date comment '入职时间',

dept_id int unsigned comment '部门ID', -- 员工的归属部门

create_time datetime not null comment '创建时间',
update_time datetime not null comment '修改时间'
) comment '员工表';

测试数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
-- 部门表测试数据
insert into tb_dept (id, name, create_time, update_time) values
(1,'学工部',now(),now()),
(2,'教研部',now(),now()),
(3,'咨询部',now(),now()),
(4,'就业部',now(),now()),
(5,'人事部',now(),now());

-- 员工表测试数据
INSERT INTO tb_emp
(id, username, password, name, gender, image, job, entrydate,dept_id, create_time, update_time) VALUES
(1,'jinyong','123456','金庸',1,'1.jpg',4,'2000-01-01',2,now(),now()),
(2,'zhangwuji','123456','张无忌',1,'2.jpg',2,'2015-01-01',2,now(),now()),
(3,'yangxiao','123456','杨逍',1,'3.jpg',2,'2008-05-01',2,now(),now()),
(4,'weiyixiao','123456','韦一笑',1,'4.jpg',2,'2007-01-01',2,now(),now()),
(5,'changyuchun','123456','常遇春',1,'5.jpg',2,'2012-12-05',2,now(),now()),
(6,'xiaozhao','123456','小昭',2,'6.jpg',3,'2013-09-05',1,now(),now()),
(7,'jixiaofu','123456','纪晓芙',2,'7.jpg',1,'2005-08-01',1,now(),now()),
(8,'zhouzhiruo','123456','周芷若',2,'8.jpg',1,'2014-11-09',1,now(),now()),
(9,'dingminjun','123456','丁敏君',2,'9.jpg',1,'2011-03-11',1,now(),now()),
(10,'zhaomin','123456','赵敏',2,'10.jpg',1,'2013-09-05',1,now(),now()),
(11,'luzhangke','123456','鹿杖客',1,'11.jpg',1,'2007-02-01',1,now(),now()),
(12,'hebiweng','123456','鹤笔翁',1,'12.jpg',1,'2008-08-18',1,now(),now()),
(13,'fangdongbai','123456','方东白',1,'13.jpg',2,'2012-11-01',2,now(),now()),
(14,'zhangsanfeng','123456','张三丰',1,'14.jpg',2,'2002-08-01',2,now(),now()),
(15,'yulianzhou','123456','俞莲舟',1,'15.jpg',2,'2011-05-01',2,now(),now()),
(16,'songyuanqiao','123456','宋远桥',1,'16.jpg',2,'2010-01-01',2,now(),now()),
(17,'chenyouliang','123456','陈友谅',1,'17.jpg',NULL,'2015-03-21',NULL,now(),now());

员工表 - 部门表之间的关系:

image-20221206230156403

一对多关系实现:在数据库表中多的一方,添加字段,来关联属于一这方的主键。

2.1.2 外键约束

问题

  • 表结构创建完毕后,我们看到两张表的数据分别为:

image-20220831201844375

现在员工表中有五个员工都归属于1号部门(学工部),当删除了1号部门后,数据变为:

image-20220831202111247

1号部门被删除了,但是依然还有5个员工是属于1号部门的。 此时:就出现数据的不完整、不一致了。

问题分析

目前上述的两张表(员工表、部门表),在数据库层面,并未建立关联,所以是无法保证数据的一致性和完整性的

问题解决

想解决上述的问题呢,我们就可以通过数据库中的 外键约束 来解决。

外键约束:让两张表的数据建立连接,保证数据的一致性和完整性。

对应的关键字:foreign key

外键约束的语法:

1
2
3
4
5
6
7
8
9
10
-- 创建表时指定
create table 表名(
字段名 数据类型,
...
[constraint] [外键名称] foreign key (外键字段名) references 主表 (主表列名)
);


-- 建完表后,添加外键
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名);

那接下来,我们就为员工表的dept_id 建立外键约束,来关联部门表的主键。

方式1:通过SQL语句操作

1
2
3
-- 修改表: 添加外键约束
alter table tb_emp
add constraint fk_dept_id foreign key (dept_id) references tb_dept(id);

方式2:图形化界面操作

image-20221206232750376

当我们添加外键约束时,我们得保证当前数据库表中的数据是完整的。 所以,我们需要将之前删除掉的数据再添加回来。

当我们添加了外键之后,再删除ID为1的部门,就会发现,此时数据库报错了,不允许删除。

外键约束(foreign key):保证了数据的完整性和一致性。

物理外键和逻辑外键

  • 物理外键

    • 概念:使用foreign key定义外键关联另外一张表。
    • 缺点:
      • 影响增、删、改的效率(需要检查外键关系)。
      • 仅用于单节点数据库,不适用与分布式、集群场景。
      • 容易引发数据库的死锁问题,消耗性能。
  • 逻辑外键

    • 概念:在业务层逻辑中,解决外键关联。
    • 通过逻辑外键,就可以很方便的解决上述问题。

**在现在的企业开发中,很少会使用物理外键,都是使用逻辑外键。 甚至在一些数据库开发规范中,会明确指出禁止使用物理外键 foreign key **

2.2 一对一

一对一关系表在实际开发中应用起来比较简单,通常是用来做单表的拆分,也就是将一张大表拆分成两张小表,将大表中的一些基础字段放在一张表当中,将其他的字段放在另外一张表当中,以此来提高数据的操作效率。

一对一的应用场景: 用户表(基本信息+身份信息)

image-20221207104508080

  • 基本信息:用户的ID、姓名、性别、手机号、学历
  • 身份信息:民族、生日、身份证号、身份证签发机关,身份证的有效期(开始时间、结束时间)

如果在业务系统当中,对用户的基本信息查询频率特别的高,但是对于用户的身份信息查询频率很低,此时出于提高查询效率的考虑,我就可以将这张大表拆分成两张小表,第一张表存放的是用户的基本信息,而第二张表存放的就是用户的身份信息。他们两者之间一对一的关系,一个用户只能对应一个身份证,而一个身份证也只能关联一个用户。

那么在数据库层面怎么去体现上述两者之间是一对一的关系呢?

其实一对一我们可以看成一种特殊的一对多。一对多我们是怎么设计表关系的?是不是在多的一方添加外键。同样我们也可以通过外键来体现一对一之间的关系,我们只需要在任意一方来添加一个外键就可以了。

image-20221207105632634

一对一 :在任意一方加入外键,关联另外一方的主键,并且设置外键为唯一的(UNIQUE)

SQL脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
-- 用户基本信息表
create table tb_user(
id int unsigned primary key auto_increment comment 'ID',
name varchar(10) not null comment '姓名',
gender tinyint unsigned not null comment '性别, 1 男 2 女',
phone char(11) comment '手机号',
degree varchar(10) comment '学历'
) comment '用户基本信息表';
-- 测试数据
insert into tb_user values (1,'白眉鹰王',1,'18812340001','初中'),
(2,'青翼蝠王',1,'18812340002','大专'),
(3,'金毛狮王',1,'18812340003','初中'),
(4,'紫衫龙王',2,'18812340004','硕士');

-- 用户身份信息表
create table tb_user_card(
id int unsigned primary key auto_increment comment 'ID',
nationality varchar(10) not null comment '民族',
birthday date not null comment '生日',
idcard char(18) not null comment '身份证号',
issued varchar(20) not null comment '签发机关',
expire_begin date not null comment '有效期限-开始',
expire_end date comment '有效期限-结束',
user_id int unsigned not null unique comment '用户ID',
constraint fk_user_id foreign key (user_id) references tb_user(id)
) comment '用户身份信息表';
-- 测试数据
insert into tb_user_card values (1,'汉','1960-11-06','100000100000100001','朝阳区公安局','2000-06-10',null,1),
(2,'汉','1971-11-06','100000100000100002','静安区公安局','2005-06-10','2025-06-10',2),
(3,'汉','1963-11-06','100000100000100003','昌平区公安局','2006-06-10',null,3),
(4,'回','1980-11-06','100000100000100004','海淀区公安局','2008-06-10','2028-06-10',4);

2.3 多对多

多对多的关系在开发中属于也比较常见的。比如:学生和老师的关系,一个学生可以有多个授课老师,一个授课老师也可以有多个学生。在比如:学生和课程的关系,一个学生可以选修多门课程,一个课程也可以供多个学生选修。

案例:学生与课程的关系

  • 关系:一个学生可以选修多门课程,一门课程也可以供多个学生选择

  • 实现关系:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键

image-20221207113341028

SQL脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
-- 学生表
create table tb_student(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '姓名',
no varchar(10) comment '学号'
) comment '学生表';
-- 学生表测试数据
insert into tb_student(name, no) values ('黛绮丝', '2000100101'),('谢逊', '2000100102'),('殷天正', '2000100103'),('韦一笑', '2000100104');

-- 课程表
create table tb_course(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '课程名称'
) comment '课程表';
-- 课程表测试数据
insert into tb_course (name) values ('Java'), ('PHP'), ('MySQL') , ('Hadoop');

-- 学生课程表(中间表)
create table tb_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_courseid foreign key (course_id) references tb_course (id),
constraint fk_studentid foreign key (student_id) references tb_student (id)
)comment '学生课程中间表';
-- 学生课程表测试数据
insert into tb_student_course(student_id, course_id) values (1,1),(1,2),(1,3),(2,2),(2,3),(3,4);

2.4 案例

下面通过一个综合案例加深对于多表关系的理解,并掌握多表设计的流程。

需求

  • 根据参考资料中提供的《苍穹外卖_管理后台》页面原型,设计分类管理、菜品管理、套餐管理模块的表结构。

步骤

  1. 阅读页面原型及需求文档,分析各个模块涉及到的表结构,及表结构之间的关系。

  2. 根据页面原型及需求文档,分析各个表结构中具体的字段及约束。

分析

  • 页面原型-分类管理

image-20221207114241260

分类的信息:分类名称、分类类型[菜品/套餐]、分类排序、分类状态[禁用/启用]、分类的操作时间(修改时间)。

  • 页面原型-菜品管理

image-20221207114300057

菜品的信息:菜品名称、菜品图片、菜品分类、菜品售价、菜品售卖状态、菜品的操作时间(修改时间)。

思考:分类与菜品之间是什么关系?

  • 思考逻辑:一个分类下可以有多个菜品吗?反过来再想一想,一个菜品会对应多个分类吗?

答案:一对多关系。一个分类下会有多个菜品,而一个菜品只能归属一个分类。

设计表原则:在多的一方,添加字段,关联属于一这方的主键。

  • 页面原型-套餐管理

image-20221207114327139

套餐的信息:套餐名称、套餐图片、套餐分类、套餐价格、套餐售卖状态、套餐的操作时间。

思考:套餐与菜品之间是什么关系?

  • 思考逻辑:一个套餐下可以有多个菜品吗?反过来再想一想,一个菜品可以出现在多个套餐中吗?

答案:多对多关系。一个套餐下会有多个菜品,而一个菜品也可以出现在多个套餐中。

设计表原则:创建第三张中间表,建立两个字段分别关联菜品表的主键和套餐表的主键。

分析页面原型及需求文档后,我们获得:

  • 分类表
    • 业务字段:分类名称、分类类型、分类排序、分类状态
    • 基础字段:id(主键)、分类的创建时间、分类的修改时间
  • 菜品表
    • 业务字段:菜品名称、菜品图片、菜品分类、菜品售价、菜品售卖状态
    • 基础字段:id(主键)、分类的创建时间、分类的修改时间
  • 套餐表
    • 业务字段:套餐名称、套餐图片、套餐分类、套餐价格、套餐售卖状态
    • 基础字段:id(主键)、分类的创建时间、分类的修改时间

表结构之间的关系:

  • 分类表 - 菜品表 : 一对多
    • 在菜品表中添加字段(菜品分类),关联分类表
  • 菜品表 - 套餐表 : 多对多
    • 创建第三张中间表(套餐菜品关联表),在中间表上添加两个字段(菜品id、套餐id),分别关联菜品表和分类表

表结构

分类表:category

  • 业务字段:分类名称、分类类型、分类排序、分类状态
  • 基础字段:id(主键)、创建时间、修改时间

image-20221207143907853

1
2
3
4
5
6
7
8
9
10
11
-- 分类表
create table category
(
id int unsigned primary key auto_increment comment '主键ID',
name varchar(20) not null unique comment '分类名称',
type tinyint unsigned not null comment '类型 1 菜品分类 2 套餐分类',
sort tinyint unsigned not null comment '顺序',
status tinyint unsigned not null default 0 comment '状态 0 禁用,1 启用',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '更新时间'
) comment '菜品及套餐分类';

菜品表:dish

  • 业务字段:菜品名称、菜品图片、菜品分类、菜品售价、菜品售卖状态
  • 基础字段:id(主键)、分类的创建时间、分类的修改时间

image-20221207144323100

1
2
3
4
5
6
7
8
9
10
11
12
13
-- 菜品表
create table dish
(
id int unsigned primary key auto_increment comment '主键ID',
name varchar(20) not null unique comment '菜品名称',
category_id int unsigned not null comment '菜品分类ID', -- 逻辑外键
price decimal(8, 2) not null comment '菜品价格',
image varchar(300) not null comment '菜品图片',
description varchar(200) comment '描述信息',
status tinyint unsigned not null default 0 comment '状态, 0 停售 1 起售',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '更新时间'
) comment '菜品';

套餐表:setmeal

  • 业务字段:套餐名称、套餐图片、套餐分类、套餐价格、套餐售卖状态
  • 基础字段:id(主键)、分类的创建时间、分类的修改时间

image-20221207144723621

1
2
3
4
5
6
7
8
9
10
11
12
13
-- 套餐表
create table setmeal
(
id int unsigned primary key auto_increment comment '主键ID',
name varchar(20) not null unique comment '套餐名称',
category_id int unsigned not null comment '分类id', -- 逻辑外键
price decimal(8, 2) not null comment '套餐价格',
image varchar(300) not null comment '图片',
description varchar(200) comment '描述信息',
status tinyint unsigned not null default 0 comment '状态 0:停用 1:启用',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '更新时间'
) comment '套餐';

套餐菜品关联表:setmeal_dish

image-20221207145016440

1
2
3
4
5
6
7
8
-- 套餐菜品关联表
create table setmeal_dish
(
id int unsigned primary key auto_increment comment '主键ID',
setmeal_id int unsigned not null comment '套餐id ', -- 逻辑外键
dish_id int unsigned not null comment '菜品id', -- 逻辑外键
copies tinyint unsigned not null comment '份数'
) comment '套餐菜品关联表';

3. 多表查询

3.1 概述

3.1.1 数据准备

SQL脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#建议:创建新的数据库
create database db04;
use db04;

-- 部门表
create table tb_dept
(
id int unsigned primary key auto_increment comment '主键ID',
name varchar(10) not null unique comment '部门名称',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '修改时间'
) comment '部门表';
-- 部门表测试
insert into tb_dept (id, name, create_time, update_time)
values (1, '学工部', now(), now()),
(2, '教研部', now(), now()),
(3, '咨询部', now(), now()),
(4, '就业部', now(), now()),
(5, '人事部', now(), now());

-- 员工表
create table tb_emp
(
id int unsigned primary key auto_increment comment 'ID',
username varchar(20) not null unique comment '用户名',
password varchar(32) default '123456' comment '密码',
name varchar(10) not null comment '姓名',
gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
image varchar(300) comment '图像',
job tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师',
entrydate date comment '入职时间',
dept_id int unsigned comment '部门ID',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '修改时间'
) comment '员工表';
-- 员工表测试数据
INSERT INTO tb_emp(id, username, password, name, gender, image, job, entrydate,dept_id, create_time, update_time)
VALUES
(1,'jinyong','123456','金庸',1,'1.jpg',4,'2000-01-01',2,now(),now()),
(2,'zhangwuji','123456','张无忌',1,'2.jpg',2,'2015-01-01',2,now(),now()),
(3,'yangxiao','123456','杨逍',1,'3.jpg',2,'2008-05-01',2,now(),now()),
(4,'weiyixiao','123456','韦一笑',1,'4.jpg',2,'2007-01-01',2,now(),now()),
(5,'changyuchun','123456','常遇春',1,'5.jpg',2,'2012-12-05',2,now(),now()),
(6,'xiaozhao','123456','小昭',2,'6.jpg',3,'2013-09-05',1,now(),now()),
(7,'jixiaofu','123456','纪晓芙',2,'7.jpg',1,'2005-08-01',1,now(),now()),
(8,'zhouzhiruo','123456','周芷若',2,'8.jpg',1,'2014-11-09',1,now(),now()),
(9,'dingminjun','123456','丁敏君',2,'9.jpg',1,'2011-03-11',1,now(),now()),
(10,'zhaomin','123456','赵敏',2,'10.jpg',1,'2013-09-05',1,now(),now()),
(11,'luzhangke','123456','鹿杖客',1,'11.jpg',5,'2007-02-01',3,now(),now()),
(12,'hebiweng','123456','鹤笔翁',1,'12.jpg',5,'2008-08-18',3,now(),now()),
(13,'fangdongbai','123456','方东白',1,'13.jpg',5,'2012-11-01',3,now(),now()),
(14,'zhangsanfeng','123456','张三丰',1,'14.jpg',2,'2002-08-01',2,now(),now()),
(15,'yulianzhou','123456','俞莲舟',1,'15.jpg',2,'2011-05-01',2,now(),now()),
(16,'songyuanqiao','123456','宋远桥',1,'16.jpg',2,'2007-01-01',2,now(),now()),
(17,'chenyouliang','123456','陈友谅',1,'17.jpg',NULL,'2015-03-21',NULL,now(),now());

3.1.2 介绍

多表查询:查询时从多张表中获取所需数据

单表查询的SQL语句:select 字段列表 from 表名;

那么要执行多表查询,只需要使用逗号分隔多张表即可,如: select 字段列表 from 表1, 表2;

查询用户表和部门表中的数据:

1
select * from  tb_emp , tb_dept;

image-20220901093654673

此时,我们看到查询结果中包含了大量的结果集,总共85条记录,而这其实就是员工表所有的记录(17行)与部门表所有记录(5行)的所有组合情况,这种现象称之为笛卡尔积。

笛卡尔积:笛卡尔乘积是指在数学中,两个集合(A集合和B集合)的所有组合情况。

image-20221207155509696

在多表查询时,需要消除无效的笛卡尔积,只保留表关联部分的数据

在SQL语句中,如何去除无效的笛卡尔积呢?只需要给多表查询加上连接查询的条件即可。

1
select * from tb_emp , tb_dept where tb_emp.dept_id = tb_dept.id ;

image-20221207164518904

由于id为17的员工,没有dept_id字段值,所以在多表查询时,根据连接查询的条件并没有查询到。

3.1.3 分类

多表查询可以分为:

  1. 连接查询

    • 内连接:相当于查询A、B交集部分数据

    image-20221207165446062

  2. 外连接

    • 左外连接:查询左表所有数据(包括两张表交集部分数据)

    • 右外连接:查询右表所有数据(包括两张表交集部分数据)

  3. 子查询

3.2 内连接

内连接查询:查询两表或多表中交集部分数据。

内连接从语法上可以分为:

  • 隐式内连接

  • 显式内连接

隐式内连接语法:

1
select  字段列表   from   表1 , 表2   where  条件 ... ;

显式内连接语法:

1
select  字段列表   from   表1  [ inner ]  join 表2  on  连接条件 ... ;

案例:查询员工的姓名及所属的部门名称

  • 隐式内连接实现
1
2
3
select tb_emp.name , tb_dept.name -- 分别查询两张表中的数据
from tb_emp , tb_dept -- 关联两张表
where tb_emp.dept_id = tb_dept.id; -- 消除笛卡尔积
  • 显式内连接实现
1
2
3
select tb_emp.name , tb_dept.name
from tb_emp inner join tb_dept
on tb_emp.dept_id = tb_dept.id;

image-20221207173435289

多表查询时给表起别名:

  • tableA as 别名1 , tableB as 别名2 ;

  • tableA 别名1 , tableB 别名2 ;

image-20221207174234522

使用了别名的多表查询:

1
2
3
select emp.name , dept.name
from tb_emp emp inner join tb_dept dept
on emp.dept_id = dept.id;

注意事项:

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

3.3 外连接

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

左外连接语法结构:

1
select  字段列表   from   表1  left  [ outer ]  join 表2  on  连接条件 ... ;

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

右外连接语法结构:

1
select  字段列表   from   表1  right  [ outer ]  join 表2  on  连接条件 ... ;

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

案例:查询员工表中所有员工的姓名, 和对应的部门名称

1
2
3
4
-- 左外连接:以left join关键字左边的表为主表,查询主表中所有数据,以及和主表匹配的右边表中的数据
select emp.name , dept.name
from tb_emp AS emp left join tb_dept AS dept
on emp.dept_id = dept.id;

image-20221207181204792

案例:查询部门表中所有部门的名称, 和对应的员工名称

1
2
3
4
-- 右外连接
select dept.name , emp.name
from tb_emp AS emp right join tb_dept AS dept
on emp.dept_id = dept.id;

image-20221207181048208

注意事项:

左外连接和右外连接是可以相互替换的,只需要调整连接查询时SQL语句中表的先后顺序就可以了。而我们在日常开发使用时,更偏向于左外连接。

3.4 子查询

3.4.1 介绍

SQL语句中嵌套select语句,称为嵌套查询,又称子查询。

1
SELECT  *  FROM   t1   WHERE  column1 =  ( SELECT  column1  FROM  t2 ... );

子查询外部的语句可以是insert / update / delete / select 的任何一个,最常见的是 select。

根据子查询结果的不同分为:

  1. 标量子查询(子查询结果为单个值[一行一列])

  2. 列子查询(子查询结果为一列,但可以是多行)

  3. 行子查询(子查询结果为一行,但可以是多列)

  4. 表子查询(子查询结果为多行多列[相当于子查询结果是一张表])

子查询可以书写的位置:

  1. where之后
  2. from之后
  3. select之后

3.4.2 标量子查询

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

常用的操作符: = <> > >= < <=

案例1:查询"教研部"的所有员工信息

可以将需求分解为两步:

  1. 查询 “教研部” 部门ID
  2. 根据 “教研部” 部门ID,查询员工信息
1
2
3
4
5
6
7
-- 1.查询"教研部"部门ID
select id from tb_dept where name = '教研部'; #查询结果:2
-- 2.根据"教研部"部门ID, 查询员工信息
select * from tb_emp where dept_id = 2;

-- 合并出上两条SQL语句
select * from tb_emp where dept_id = (select id from tb_dept where name = '教研部');

image-20221207202215946

案例2:查询在 “方东白” 入职之后的员工信息

可以将需求分解为两步:

  1. 查询 方东白 的入职日期
  2. 查询 指定入职日期之后入职的员工信息
1
2
3
4
5
6
7
-- 1.查询"方东白"的入职日期
select entrydate from tb_emp where name = '方东白'; #查询结果:2012-11-01
-- 2.查询指定入职日期之后入职的员工信息
select * from tb_emp where entrydate > '2012-11-01';

-- 合并以上两条SQL语句
select * from tb_emp where entrydate > (select entrydate from tb_emp where name = '方东白');

image-20221207203000445

3.4.3 列子查询

子查询返回的结果是一列(可以是多行),这种子查询称为列子查询。

常用的操作符:

操作符 描述
IN 在指定的集合范围之内,多选一
NOT IN 不在指定的集合范围之内

案例:查询"教研部"和"咨询部"的所有员工信息

分解为以下两步:

  1. 查询 “销售部” 和 “市场部” 的部门ID
  2. 根据部门ID, 查询员工信息
1
2
3
4
5
6
7
-- 1.查询"销售部"和"市场部"的部门ID
select id from tb_dept where name = '教研部' or name = '咨询部'; #查询结果:3,2
-- 2.根据部门ID, 查询员工信息
select * from tb_emp where dept_id in (3,2);

-- 合并以上两条SQL语句
select * from tb_emp where dept_id in (select id from tb_dept where name = '教研部' or name = '咨询部');

image-20221207203620472

3.4.4 行子查询

子查询返回的结果是一行(可以是多列),这种子查询称为行子查询。

常用的操作符:= 、<> 、IN 、NOT IN

案例:查询与"韦一笑"的入职日期及职位都相同的员工信息

可以拆解为两步进行:

  1. 查询 “韦一笑” 的入职日期 及 职位
  2. 查询与"韦一笑"的入职日期及职位相同的员工信息
1
2
3
4
5
6
7
-- 查询"韦一笑"的入职日期 及 职位
select entrydate , job from tb_emp where name = '韦一笑'; #查询结果: 2007-01-01 , 2
-- 查询与"韦一笑"的入职日期及职位相同的员工信息
select * from tb_emp where (entrydate,job) = ('2007-01-01',2);

-- 合并以上两条SQL语句
select * from tb_emp where (entrydate,job) = (select entrydate , job from tb_emp where name = '韦一笑');

image-20221207204452202

3.4.5 表子查询

子查询返回的结果是多行多列,常作为临时表,这种子查询称为表子查询。

案例:查询入职日期是 “2006-01-01” 之后的员工信息 , 及其部门信息

分解为两步执行:

  1. 查询入职日期是 “2006-01-01” 之后的员工信息
  2. 基于查询到的员工信息,在查询对应的部门信息
1
2
3
4
5
6
7
8
9
10
select * from emp where entrydate > '2006-01-01';

select e.*, d.* from
(select * from emp where entrydate > '2006-01-01') e ,dept d
where e.dept_id = d.id ;

select e.*, d.* from
(select * from emp where entrydate > '2006-01-01') e
left join dept d
on e.dept_id = d.id ;

image-20221208142154263

3.5 案例

基于之前设计的多表案例的表结构,我们来完成今天的多表查询案例需求。

准备环境

将资料中准备好的多表查询的数据准备的SQL脚本导入数据库中。

image-20221208143318921

  • 分类表:category
  • 菜品表:dish
  • 套餐表:setmeal
  • 套餐菜品关系表:setmeal_dish

image-20221208143312292

需求实现

  1. 查询价格低于 10元 的菜品的名称 、价格 及其 菜品的分类名称
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*查询技巧:
明确1:查询需要用到哪些字段
菜品名称、菜品价格 、 菜品分类名
明确2:查询的字段分别归属于哪张表
菜品表:[菜品名称、菜品价格]
分类表:[分类名]
明确3:如查多表,建立表与表之间的关联
菜品表.caategory_id = 分类表.id
其他:(其他条件、其他要求)
价格 < 10
*/
select d.name , d.price , c.name
from dish AS d , category AS c
where d.category_id = c.id
and d.price < 10;

image-20221208145036602

  1. 查询所有价格在 10元(含)到50元(含)之间 且 状态为"起售"的菜品名称、价格及其分类名称 (即使菜品没有分类 , 也要将菜品查询出来)
1
2
3
4
select d.name , d.price, c.name
from dish AS d left join category AS c on d.category_id = c.id
where d.price between 10 and 50
and d.status = 1;

image-20221208145432077

  1. 查询每个分类下最贵的菜品, 展示出分类的名称、最贵的菜品的价格
1
2
3
4
select c.name , max(d.price)
from dish AS d , category AS c
where d.category_id = c.id
group by c.name;

image-20221208150016895

  1. 查询各个分类下 菜品状态为 “起售” , 并且 该分类下菜品总数量大于等于3 的 分类名称
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*查询技巧:
明确1:查询需要用到哪些字段
分类名称、菜品总数量
明确2:查询用到的字段分别归属于哪张表
分类表:[分类名]
菜品表:[菜品状态]
明确3:如查多表,建立表与表之间的关联
菜品表.caategory_id = 分类表.id
其他:(其他条件、其他要求)
条件:菜品状态 = 1 (1表示起售)
分组:分类名
分组后条件: 总数量 >= 3
*/
select c.name , count(*)
from dish AS d , category AS c
where d.category_id = c.id
and d.status = 1 -- 起售状态
group by c.name -- 按照分类名分组
having count(*)>=3; -- 各组后筛选菜品总数据>=3

image-20221208152107502

  1. 查询出 “商务套餐A” 中包含了哪些菜品 (展示出套餐名称、价格, 包含的菜品名称、价格、份数)
1
2
3
4
select s.name, s.price, d.name, d.price, sd.copies
from setmeal AS s , setmeal_dish AS sd , dish AS d
where s.id = sd.setmeal_id and sd.dish_id = d.id
and s.name='商务套餐A';

image-20221208152626138

  1. 查询出低于菜品平均价格的菜品信息 (展示出菜品名称、菜品价格)
1
2
3
4
5
6
7
-- 1.计算菜品平均价格
select avg(price) from dish; -- 查询结果:37.736842
-- 2.查询出低于菜品平均价格的菜品信息
select * from dish where price < 37.736842;

-- 合并以上两条SQL语句
select * from dish where price < (select avg(price) from dish);

image-20221208153051333

4. 事务

场景:学工部整个部门解散了,该部门及部门下的员工都需要删除了。

  • 操作:

    1
    2
    3
    4
    5
    -- 删除学工部
    delete from dept where id = 1; -- 删除成功

    -- 删除学工部的员工
    delete from emp where dept_id = 1; -- 删除失败(操作过程中出现错误:造成删除没有成功)
  • 问题:如果删除部门成功了,而删除该部门的员工时失败了,此时就造成了数据的不一致。

​ 要解决上述的问题,就需要通过数据库中的事务来解决。

4.1 介绍

在实际的业务开发中,有些业务操作要多次访问数据库。一个业务要发送多条SQL语句给数据库执行。需要将多次访问数据库的操作视为一个整体来执行,要么所有的SQL语句全部执行成功。如果其中有一条SQL语句失败,就进行事务的回滚,所有的SQL语句全部执行失败。

简而言之:事务是一组操作的集合,它是一个不可分割的工作单位。事务会把所有的操作作为一个整体一起向系统提交或撤销操作请求,即这些操作要么同时成功,要么同时失败。

事务作用:保证在一个事务中多次操作数据库表中数据时,要么全都成功,要么全都失败。

4.2 操作

MYSQL中有两种方式进行事务的操作:

  1. 自动提交事务:即执行一条sql语句提交一次事务。(默认MySQL的事务是自动提交)
  2. 手动提交事务:先开启,再提交

事务操作有关的SQL语句:

SQL语句 描述
start transaction; / begin ; 开启手动控制事务
commit; 提交事务
rollback; 回滚事务

手动提交事务使用步骤:

  • 第1种情况:开启事务 => 执行SQL语句 => 成功 => 提交事务
  • 第2种情况:开启事务 => 执行SQL语句 => 失败 => 回滚事务

使用事务控制删除部门和删除该部门下的员工的操作:

1
2
3
4
5
6
7
8
-- 开启事务
start transaction ;

-- 删除学工部
delete from tb_dept where id = 1;

-- 删除学工部的员工
delete from tb_emp where dept_id = 1;
  • 上述的这组SQL语句,如果如果执行成功,则提交事务
1
2
-- 提交事务 (成功时执行)
commit ;
  • 上述的这组SQL语句,如果如果执行失败,则回滚事务
1
2
-- 回滚事务 (出错时执行)
rollback ;

4.3 四大特性

面试题:事务有哪些特性?

  • 原子性(Atomicity):事务是不可分割的最小单元,要么全部成功,要么全部失败。
  • 一致性(Consistency):事务完成时,必须使所有的数据都保持一致状态。
  • 隔离性(Isolation):数据库系统提供的隔离机制,保证事务在不受外部并发操作影响的独立环境下运行。
  • 持久性(Durability):事务一旦提交或回滚,它对数据库中的数据的改变就是永久的。

事务的四大特性简称为:ACID

  • 原子性(Atomicity) :原子性是指事务包装的一组sql是一个不可分割的工作单元,事务中的操作要么全部成功,要么全部失败。

  • 一致性(Consistency):一个事务完成之后数据都必须处于一致性状态。

​ 如果事务成功的完成,那么数据库的所有变化将生效。

​ 如果事务执行出现错误,那么数据库的所有变化将会被回滚(撤销),返回到原始状态。

  • 隔离性(Isolation):多个用户并发的访问数据库时,一个用户的事务不能被其他用户的事务干扰,多个并发的事务之间要相互隔离。

​ 一个事务的成功或者失败对于其他的事务是没有影响。

  • 持久性(Durability):一个事务一旦被提交或回滚,它对数据库的改变将是永久性的,哪怕数据库发生异常,重启之后数据亦然存在。

4. 索引

4.1 介绍

索引(index):是帮助数据库高效获取数据的数据结构 。

  • 简单来讲,就是使用索引可以提高查询的效率。

测试没有使用索引的查询:

image-20221209115617429

添加索引后查询:

1
2
3
4
5
-- 添加索引
create index idx_sku_sn on tb_sku (sn); #在添加索引时,也需要消耗时间

-- 查询数据(使用了索引)
select * from tb_sku where sn = '100000003145008';

image-20221209120107543

优点:

  1. 提高数据查询的效率,降低数据库的IO成本。
  2. 通过索引列对数据进行排序,降低数据排序的成本,降低CPU消耗。

缺点:

  1. 索引会占用存储空间。
  2. 索引大大提高了查询效率,同时却也降低了insert、update、delete的效率。

4.2 结构

MySQL数据库支持的索引结构有很多,如:Hash索引、B+Tree索引、Full-Text索引等。

我们平常所说的索引,如果没有特别指明,都是指默认的 B+Tree 结构组织的索引。

在没有了解B+Tree结构前,我们先回顾下之前所学习的树结构:

二叉查找树:左边的子节点比父节点小,右边的子节点比父节点大

image-20221208174135229

当我们向二叉查找树保存数据时,是按照从大到小(或从小到大)的顺序保存的,此时就会形成一个单向链表,搜索性能会打折扣。

image-20221208174859866

可以选择平衡二叉树或者是红黑树来解决上述问题。(红黑树也是一棵平衡的二叉树)

image-20221209100647867

但是在Mysql数据库中并没有使用二叉搜索数或二叉平衡数或红黑树来作为索引的结构。

思考:采用二叉搜索树或者是红黑树来作为索引的结构有什么问题?

答案 最大的问题就是在数据量大的情况下,树的层级比较深,会影响检索速度。因为不管是二叉搜索数还是红黑数,一个节点下面只能有两个子节点。此时在数据量大的情况下,就会造成数的高度比较高,树的高度一旦高了,检索速度就会降低。

说明:如果数据结构是红黑树,那么查询1000万条数据,根据计算树的高度大概是23左右,这样确实比之前的方式快了很多,但是如果高并发访问,那么一个用户有可能需要23次磁盘IO,那么100万用户,那么会造成效率极其低下。所以为了减少红黑树的高度,那么就得增加树的宽度,就是不再像红黑树一样每个节点只能保存一个数据,可以引入另外一种数据结构,一个节点可以保存多个数据,这样宽度就会增加从而降低树的高度。这种数据结构例如BTree就满足。

下面我们来看看B+Tree(多路平衡搜索树)结构中如何避免这个问题:

image-20221208181315728

B+Tree结构:

  • 每一个节点,可以存储多个key(有n个key,就有n个指针)
  • 节点分为:叶子节点、非叶子节点
    • 叶子节点,就是最后一层子节点,所有的数据都存储在叶子节点上
    • 非叶子节点,不是树结构最下面的节点,用于索引数据,存储的的是:key+指针
  • 为了提高范围查询效率,叶子节点形成了一个双向链表,便于数据的排序及区间范围查询

拓展:

非叶子节点都是由key+指针域组成的,一个key占8字节,一个指针占6字节,而一个节点总共容量是16KB,那么可以计算出一个节点可以存储的元素个数:16*1024字节 / (8+6)=1170个元素。

  • 查看mysql索引节点大小:show global status like ‘innodb_page_size’; – 节点大小:16384

当根节点中可以存储1170个元素,那么根据每个元素的地址值又会找到下面的子节点,每个子节点也会存储1170个元素,那么第二层即第二次IO的时候就会找到数据大概是:1170*1170=135W。也就是说B+Tree数据结构中只需要经历两次磁盘IO就可以找到135W条数据。

对于第二层每个元素有指针,那么会找到第三层,第三层由key+数据组成,假设key+数据总大小是1KB,而每个节点一共能存储16KB,所以一个第三层一个节点大概可以存储16个元素(即16条记录)。那么结合第二层每个元素通过指针域找到第三层的节点,第二层一共是135W个元素,那么第三层总元素大小就是:135W*16结果就是2000W+的元素个数。

结合上述分析B+Tree有如下优点:

  • 千万条数据,B+Tree可以控制在小于等于3的高度
  • 所有的数据都存储在叶子节点上,并且底层已经实现了按照索引进行排序,还可以支持范围查询,叶子节点是一个双向链表,支持从小到大或者从大到小查找

.3 语法

创建索引

1
create  [ unique ]  index 索引名 on  表名 (字段名,... ) ;

案例:为tb_emp表的name字段建立一个索引

1
create index idx_emp_name on tb_emp(name);

image-20221209105119159

在创建表时,如果添加了主键和唯一约束,就会默认创建:主键索引、唯一约束

image-20221209105846211

查看索引

1
show  index  from  表名;

案例:查询 tb_emp 表的索引信息

1
show  index  from  tb_emp;

image-20221209110317092

删除索引

1
drop  index  索引名  on  表名;

案例:删除 tb_emp 表中name字段的索引

1
drop index idx_emp_name on tb_emp;

注意事项:

  • 主键字段,在建表时,会自动创建主键索引

  • 添加唯一约束时,数据库实际上会添加唯一索引