mysql基础到源码详解

1.聚合函数

1). 介绍
将一列数据作为一个整体,进行纵向计算 。
2). 常见的聚合函数

2.分组查询

3.排序查询

4.分页查询

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

5.SQL执行顺序

在讲解 DQL 语句的具体语法之前,我们已经讲解了 DQL 语句的完整语法,及编写顺序,接下来,我们要
来说明的是DQL语句在执行时的执行顺序,也就是先执行那一部分,后执行那一部分

6.函数

函数 是指一段可以直接被另一段程序调用的程序或代码。 也就意味着,这一段程序或代码在 MySQL
已经给我们提供了,我们要做的就是在合适的业务场景调用对应的函数完成对应的业务需求即可。 那
么,函数到底在哪儿使用呢?
我们先来看两个场景:

7.字符串函数

MySQL中内置了很多字符串函数,常用的几个如下:
由于业务需求变更,企业员工的工号,统一为 5 位数,目前不足 5 位数的全部在前面补 0 。比如: 1 号员
工的工号应该为00001。

8.数值函数

9.流程控制函数

流程函数也是很常用的一类函数,可以在SQL语句中实现条件筛选,从而提高语句的效率。
案例:

10.约束

概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据。
目的:保证数据库中数据的正确、有效性和完整性。
分类:
上面我们介绍了数据库中常见的约束,以及约束涉及到的关键字,那这些约束我们到底如何在创建表、
修改表的时候来指定呢,接下来我们就通过一个案例,来演示一下。
案例需求: 根据需求,完成表结构的创建。需求如下:

11.多表查询

对应的 SQL 脚本 :
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');
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, 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);
一对一
案例 : 用户 与 用户详情的关系
关系 : 一对一关系,多用于单表拆分,将一张表的基础字段放在一张表中,其他详情字段放在另
一张表中,以提升操作效率
实现 : 在任意一方加入外键,关联另外一方的主键,并且设置外键为唯一的 (UNIQUE)
对应的 SQL 脚本 :
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_edu(
id int auto_increment primary key comment ' 主键 ID' ,
degree varchar ( 20 ) comment ' 学历 ' ,
major varchar ( 50 ) comment ' 专业 ' ,
primaryschool varchar ( 50 ) comment ' 小学 ' ,
middleschool varchar ( 50 ) comment ' 中学 ' ,
university varchar ( 50 ) comment ' 大学 ' ,
userid int unique comment ' 用户 ID' ,
constraint fk_userid foreign key (userid) 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_edu(id, degree, major, primaryschool, middleschool,
university, userid) values
( null , ' 本科 ' , ' 舞蹈 ' , ' 静安区第一小学 ' , ' 静安区第一中学 ' , ' 北京舞蹈学院 ' , 1 ),
( null , ' 硕士 ' , ' 表演 ' , ' 朝阳区第一小学 ' , ' 朝阳区第一中学 ' , ' 北京电影学院 ' , 2 ),
( null , ' 本科 ' , ' 英语 ' , ' 杭州市第一小学 ' , ' 杭州市第一中学 ' , ' 杭州师范大学 ' , 3 ),
( null , ' 本科 ' , ' 应用数学 ' , ' 阳泉第一小学 ' , ' 阳泉区第一中学 ' , ' 清华大学 ' , 4 );
5.2 多表查询概述
5.2.1 数据准备
1). 删除之前 emp, dept 表的测试数据
2). 执行如下脚本,创建 emp 表与 dept 表并插入测试数据
-- 创建 dept 表,并插入数据
create table dept(
id int auto_increment comment 'ID' primary key,
name varchar ( 50 ) not null comment ' 部门名称 '
)comment ' 部门表 ' ;
INSERT INTO dept (id, name) VALUES ( 1 , ' 研发部 ' ), ( 2 , ' 市场部 ' ),( 3 , ' 财务部 ' ), ( 4 ,
' 销售部 ' ), ( 5 , ' 总经办 ' ), ( 6 , ' 人事部 ' );
-- 创建 emp 表,并插入数据
create table emp(
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' ,
dept_id int comment ' 部门 ID'
)comment ' 员工表 ' ;
-- 添加外键
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references
dept(id);
INSERT INTO emp (id, name, age, job,salary, entrydate, managerid, dept_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集合的所有组合情况。
而在多表查询中,我们是需要消除无效的笛卡尔积的,只保留两张表关联部分的数据。
SQL 语句中,如何来去除无效的笛卡尔积呢? 我们可以给多表查询加上连接查询的条件即可。
select * from emp , dept where emp.dept_id = dept.id;
而由于 id 17 的员工,没有 dept_id 字段值,所以在多表查询时,根据连接查询的条件并没有查询
到。

分类

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

内连接

内连接的语法分为两种 : 隐式内连接、显式内连接。先来学习一下具体的语法结构。
1). 隐式内连接
SELECT 字段列表 FROM 1 , 2 WHERE 条件 ... ;
2). 显式内连接
SELECT 字段列表 FROM 1 [ INNER ] JOIN 2 ON 连接条件 ... ;
案例:
A. 查询每一个员工的姓名 , 及关联的部门的名称 ( 隐式内连接实现 )
表结构 : emp , dept
连接条件 : emp.dept_id = dept.id
select emp .name , dept .name from emp , dept where emp .dept_id = dept .id ;
-- 为每一张表起别名 , 简化 SQL 编写
select e .name ,d .name from emp e , dept d where e .dept_id = d .id ;
B. 查询每一个员工的姓名 , 及关联的部门的名称 ( 显式内连接实现 ) --- INNER JOIN ... ON ...
表结构 : emp , dept
连接条件 : emp.dept_id = dept.id
select e .name , d .name from emp e inner join dept d on e .dept_id = d .id ;
-- 为每一张表起别名 , 简化 SQL 编写
select e .name , d .name from emp e join dept d on e .dept_id = d .id ;

外连接

外连接分为两种,分别是:左外连接 和 右外连接。具体的语法结构为:
1). 左外连接
SELECT 字段列表 FROM 1 LEFT [ OUTER ] JOIN 2 ON 条件 ... ;
左外连接相当于查询表 1( 左表 ) 的所有数据,当然也包含表 1 和表 2 交集部分的数据。

2). 右外连接
SELECT 字段列表 FROM 1 RIGHT [ OUTER ] JOIN 2 ON 条件 ... ;
右外连接相当于查询表 2( 右表 ) 的所有数据,当然也包含表 1 和表 2 交集部分的数据。
案例 :
A. 查询 emp 表的所有数据 , 和对应的部门信息
由于需求中提到,要查询 emp 的所有数据,所以是不能内连接查询的,需要考虑使用外连接查询。
表结构 : emp, dept
连接条件 : emp.dept_id = dept.id
select e.*, d .name from emp e left outer join dept d on e .dept_id = d .id ;
select e.*, d .name from emp e left join dept d on e .dept_id = d .id ;
B. 查询 dept 表的所有数据 , 和对应的员工信息 ( 右外连接 )
由于需求中提到,要查询 dept 表的所有数据,所以是不能内连接查询的,需要考虑使用外连接查
询。
表结构 : emp, dept
连接条件 : emp.dept_id = dept.id
select d.*, e.* from emp e right outer join dept d on e .dept_id = d .id ;
select d.*, e.* from dept d left outer join emp e on e .dept_id = d .id ;
注意事项:
左外连接和右外连接是可以相互替换的,只需要调整在连接查询时 SQL 中,表结构的先后顺
序就可以了。而我们在日常开发使用时,更偏向于左外连接。

自连接

自连接查询
自连接查询,顾名思义,就是自己连接自己,也就是把一张表连接查询多次。我们先来学习一下自连接
的查询语法:
SELECT 字段列表 FROM A 别名 A JOIN A 别名 B ON 条件 ... ;
而对于自连接查询,可以是内连接查询,也可以是外连接查询。
案例:
A. 查询员工 及其 所属领导的名字
表结构 : emp
select a .name , b .name from emp a , emp b where a .managerid = b .id ;
B. 查询所有员工 emp 及其领导的名字 emp , 如果员工没有领导 , 也需要查询出来
表结构 : emp a , emp b
select a .name ' 员工 ' , b .name ' 领导 ' from emp a left join emp b on a .managerid =
b .id ;
注意事项 :
在自连接查询中,必须要为表起别名,要不然我们不清楚所指定的条件、返回的字段,到底
是哪一张表的字段。
联合查询
对于 union 查询,就是把多次查询的结果合并起来,形成一个新的查询结果集。
SELECT 字段列表 FROM A ...
UNION [ ALL ]
SELECT 字段列表 FROM B ....;
对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致。
union all 会将全部的数据直接合并在一起, union 会对合并之后的数据去重。
案例 :
A. 将薪资低于 5000 的员工 , 和 年龄大于 50 岁的员工全部查询出来 .
当前对于这个需求,我们可以直接使用多条件查询,使用逻辑运算符 or 连接即可。 那这里呢,我们
也可以通过 union/union all 来联合查询 .
select * from emp where salary < 5000
union all
select * from emp where age > 50 ;
union all 查询出来的结果,仅仅进行简单的合并,并未去重。
select * from emp where salary < 5000
union
select * from emp where age > 50 ;
union 联合查询,会对查询出来的结果进行去重处理。
注意:
如果多条查询语句查询出来的结果,字段数量不一致,在进行 union/union all 联合查询时,将会报
错。如

子查询

1). 概念
SQL 语句中嵌套 SELECT 语句,称为嵌套查询,又称子查询。
SELECT * FROM t1 WHERE column1 = ( SELECT column1 FROM t2 );
子查询外部的语句可以是 INSERT / UPDATE / DELETE / SELECT 的任何一个。
2). 分类
根据子查询结果不同,分为:
A. 标量子查询(子查询结果为单个值)
B. 列子查询 ( 子查询结果为一列 )
C. 行子查询 ( 子查询结果为一行 )
D. 表子查询 ( 子查询结果为多行多列 )
根据子查询位置,分为:
A. WHERE 之后
B. FROM 之后
C. SELECT 之后
标量子查询
子查询返回的结果是单个值(数字、字符串、日期等),最简单的形式,这种子查询称为标量子查询。
常用的操作符: = <> > >= < <=
案例 :
A. 查询 " 销售部 " 的所有员工信息
完成这个需求时,我们可以将需求分解为两步:
. 查询 " 销售部 " 部门 ID
. 根据 " 销售部 " 部门 ID, 查询员工信息
B. 查询在 " 方东白 " 入职之后的员工信息
完成这个需求时,我们可以将需求分解为两步:
. 查询 方东白 的入职日期
select id from dept where name = ' 销售部 ' ;
1
select * from emp where dept_id = ( select id from dept where name = ' 销售部 ' );
1 操作符
描述
IN
在指定的集合范围之内,多选一
NOT IN
不在指定的集合范围之内
ANY
子查询返回列表中,有任意一个满足即可
SOME
ANY 等同,使用 SOME 的地方都可以使用 ANY
ALL
子查询返回列表的所有值都必须满足
. 查询指定入职日期之后入职的员工信息
列子查询
子查询返回的结果是一列(可以是多行),这种子查询称为列子查询。
常用的操作符: IN NOT IN ANY SOME ALL
案例 :
A. 查询 " 销售部 " " 市场部 " 的所有员工信息
分解为以下两步 :
. 查询 " 销售部 " " 市场部 " 的部门 ID
. 根据部门 ID, 查询员工信息
B. 查询比 财务部 所有人工资都高的员工信息
select entrydate from emp where name = ' 方东白 ' ;
1
select * from emp where entrydate > ( select entrydate from emp where name = ' 方东
' );
行子查询
子查询返回的结果是一行(可以是多列),这种子查询称为行子查询。
常用的操作符: = <> IN NOT IN
案例 :
A. 查询与 " 张无忌 " 的薪资及直属领导相同的员工信息 ;
这个需求同样可以拆解为两步进行 :
. 查询 " 张无忌 " 的薪资及直属领导
select salary, managerid from emp where name = ' 张无忌 ' ;
. 查询与 " 张无忌 " 的薪资及直属领导相同的员工信息 ;
select * from emp where (salary,managerid) = ( select salary, managerid from emp
where name = ' 张无忌 ' );

多表查询案例

数据环境准备 :
create table salgrade(
grade int ,
losal int ,
hisal int
) comment ' 薪资等级表 ' ;
insert into salgrade values ( 1 , 0 , 3000 );
insert into salgrade values ( 2 , 3001 , 5000 );
insert into salgrade values ( 3 , 5001 , 8000 );
insert into salgrade values ( 4 , 8001 , 10000 );
insert into salgrade values ( 5 , 10001 , 15000 );
insert into salgrade values ( 6 , 15001 , 20000 );
insert into salgrade values ( 7 , 20001 , 25000 );
insert into salgrade values ( 8 , 25001 , 30000 );
在这个案例中,我们主要运用上面所讲解的多表查询的语法,完成以下的 12 个需求即可,而这里主要涉
及到的表就三张: emp 员工表、 dept 部门表、 salgrade 薪资等级表 。
1). 查询员工的姓名、年龄、职位、部门信息 (隐式内连接)
: emp , dept
连接条件 : emp.dept_id = dept.id
select e .name , e .age , e .job , d .name from emp e , dept d where e .dept_id = d .id ;
2). 查询年龄小于 30 岁的员工的姓名、年龄、职位、部门信息(显式内连接)
: emp , dept
连接条件 : emp.dept_id = dept.id
select e .name , e .age , e .job , d .name from emp e inner join dept d on e .dept_id =
d .id where e .age < 30 ;
3). 查询拥有员工的部门 ID 、部门名称
: emp , dept
连接条件 : emp.dept_id = dept.id
select distinct d .id , d .name from emp e , dept d where e .dept_id = d .id ;
4). 查询所有年龄大于 40 岁的员工 , 及其归属的部门名称 ; 如果员工没有分配部门 , 也需要展示出
( 外连接 )
: emp , dept
连接条件 : emp.dept_id = dept.id
select e.*, d .name from emp e left join dept d on e .dept_id = d .id where e .age >
40 ;
5). 查询所有员工的工资等级
: emp , salgrade
连接条件 : emp.salary >= salgrade.losal and emp.salary <= salgrade.hisal
-- 方式一
select e.* , s .grade , s .losal , s .hisal from emp e , salgrade s where e .salary >=
s .losal and e .salary <= s .hisal ;
-- 方式二
select e.* , s .grade , s .losal , s .hisal from emp e , salgrade s where e .salary
between s .losal and s .hisal ;
6). 查询 " 研发部 " 所有员工的信息及 工资等级
: emp , salgrade , dept
连接条件 : emp.salary between salgrade.losal and salgrade.hisal ,
emp.dept_id = dept.id
查询条件 : dept.name = ' 研发部 '
select e.* , s .grade from emp e , dept d , salgrade s where e .dept_id = d .id and (
e .salary between s .losal and s .hisal ) and d .name = ' 研发部 ' ;
7). 查询 " 研发部 " 员工的平均工资
: emp , dept
连接条件 : emp.dept_id = dept.id
select avg(e .salary ) from emp e, dept d where e .dept_id = d .id and d .name = ' 研发
' ;
8). 查询工资比 " 灭绝 " 高的员工信息。
. 查询 " 灭绝 " 的薪资
select salary from emp where name = ' 灭绝 ' ;
. 查询比她工资高的员工数据
select * from emp where salary > ( select salary from emp where name = ' 灭绝 ' );
9). 查询比平均薪资高的员工信息
. 查询员工的平均薪资
select avg(salary) from emp;
. 查询比平均薪资高的员工信息
select * from emp where salary > ( select avg(salary) from emp );
10). 查询低于本部门平均工资的员工信息
. 查询指定部门平均薪资
select avg(e1 .salary ) from emp e1 where e1 .dept_id = 1 ;
select avg(e1 .salary ) from emp e1 where e1 .dept_id = 2 ;
. 查询低于本部门平均工资的员工信息
select * from emp e2 where e2 .salary < ( select avg(e1 .salary ) from emp e1 where
e1 .dept_id = e2 .dept_id );
11). 查询所有的部门信息 , 并统计部门的员工人数
select d .id , d .name , ( select count (*) from emp e where e .dept_id = d .id ) ' 人数 '
from dept d;
12). 查询所有学生的选课情况 , 展示出学生名称 , 学号 , 课程名称
: student , course , student_course
连接条件 : student.id = student_course.studentid , course.id =
student_course.courseid
select s .name , s .no , c .name from student s , student_course sc , course c where
s .id = sc .studentid and sc .courseid = c .id ;

12.存储引擎

13.为什么存储引擎使用B+Tree

14.索引分类

15.索引语法

建表语句和数据

create table tb_users(
    id int primary key auto_increment comment '主键',
    name varchar(50) not null comment '用户名',
    phone varchar(11) not null comment '手机号',
    email varchar(100) comment '邮箱',
    profession varchar(11) comment '专业',
    age tinyint unsigned comment '年龄',
    gender char(1) comment '性别 , 1: 男, 2: 女',
    status char(1) comment '状态',
    createtime datetime comment '创建时间'
) comment '系统用户表';


INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('吕布', '17799990000', 'lvbu666@163.com', '软件工程', 23, '1', '6', '2001-02-02 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('曹操', '17799990001', 'caocao666@qq.com', '通讯工程', 33, '1', '0', '2001-03-05 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('赵云', '17799990002', '17799990@139.com', '英语', 34, '1', '2', '2002-03-02 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('孙悟空', '17799990003', '17799990@sina.com', '工程造价', 54, '1', '0', '2001-07-02 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('花木兰', '17799990004', '19980729@sina.com', '软件工程', 23, '2', '1', '2001-04-22 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('大乔', '17799990005', 'daqiao666@sina.com', '舞蹈', 22, '2', '0', '2001-02-07 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('露娜', '17799990006', 'luna_love@sina.com', '应用数学', 24, '2', '0', '2001-02-08 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('程咬金', '17799990007', 'chengyaojin@163.com', '化工', 38, '1', '5', '2001-05-23 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('项羽', '17799990008', 'xiaoyu666@qq.com', '金属材料', 43, '1', '0', '2001-09-18 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('白起', '17799990009', 'baiqi666@sina.com', '机械工程及其自动化', 27, '1', '2', '2001-08-16 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('韩信', '17799990010', 'hanxin520@163.com', '无机非金属材料工程', 27, '1', '0', '2001-06-12 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('荆轲', '17799990011', 'jingke123@163.com', '会计', 29, '1', '0', '2001-05-11 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('兰陵王', '17799990012', 'lanlinwang666@126.com', '工程造价', 44, '1', '1', '2001-04-09 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('狂铁', '17799990013', 'kuangtie@sina.com', '应用数学', 43, '1', '2', '2001-04-10 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('貂蝉', '17799990014', '84958948374@qq.com', '软件工程', 40, '2', '3', '2001-02-12 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('妲己', '17799990015', '2783238293@qq.com', '软件工程', 31, '2', '0', '2001-01-30 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('芈月', '17799990016', 'xiaomin2001@sina.com', '工业经济', 35, '2', '0', '2000-05-03 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('嬴政', '17799990017', '8839434342@qq.com', '化工', 38, '1', '1', '2001-08-08 00:00:00');
-- INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('狄仁杰', '17799990018', 'jujiamlm8166@163.com', '国际贸易', 30, '1', '0', '2007-03-12 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('安琪拉', '17799990019', 'jdodm1h@126.com', '城市规划', 51, '2', '0', '2001-08-15 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('典韦', '17799990020', 'ycaunanjian@163.com', '城市规划', 52, '1', '2', '2000-04-12 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('廉颇', '17799990021', 'lianpo321@126.com', '土木工程', 19, '1', '3', '2002-07-18 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('后羿', '17799990022', 'altycj2000@139.com', '城市园林', 20, '1', '0', '2002-03-10 00:00:00');
INSERT INTO mybatis.tb_users (name, phone, email, profession, age, gender, status, createtime) VALUES ('姜子牙', '17799990023', '37483844@qq.com', '工程造价', 29, '1', '4', '2003-05-26 00:00:00');

表索引查看

SHOW INDEX FROM tb_users;

按照下面要求,完成索引的创建

A. name 字段为姓名字段,该字段的值可能会重复,为该字段创建索引。
CREATE INDEX idx_users_name ON tb_users(name);
#idx_users_name  :索引名称
# tb_users(name):哪张表的哪个字段
B. phone 手机号字段的值,是非空,且唯一的,为该字段创建唯一索引。
CREATE UNIQUE INDEX idx_users_phone ON tb_users(phone);
#和常规索引唯一不同的就是加上了unique关键字
C. profession age status 创建联合索引。
CREATE INDEX idx_users_pro_age_sta ON tb_users(profession,age,status);
D. email 建立合适的索引来提升查询效率。
CREATE INDEX idx_users_email ON tb_users(email);

删除索引

DROP INDEX idx_users_email ON tb_users;

16.性能分析-SQL性能工具

SQL执行频率

MySQL 客户端连接成功后,通过 show [session|global] status 命令可以提供服务器状态信
息。通过如下指令,可以查看当前数据库的 INSERT UPDATE DELETE SELECT 的访问频次:
-- session 是查看当前会话 ;
-- global 是查询全局数据 ;
SHOW GLOBAL STATUS LIKE 'Com_______' ;->七个下划线
通过上述指令,我们可以查看到当前数据库到底是以查询为主,还是以增删改为主,从而为数据
库优化提供参考依据。 如果是以增删改为主,我们可以考虑不对其进行索引的优化。 如果是以
查询为主,那么就要考虑对数据库的索引进行优化了。
那么通过查询 SQL 的执行频次,我们就能够知道当前数据库到底是增删改为主,还是查询为主。 那假
如说是以查询为主,我们又该如何定位针对于那些查询语句进行优化呢? 次数我们可以借助于慢查询
日志。

性能分析-慢查询日志

慢查询日志记录了所有执行时间超过指定参数( long_query_time ,单位:秒,默认 10 秒)的所有
SQL 语句的日志。
MySQL 的慢查询日志默认没有开启,我们可以查看一下系统变量 slow_query_log

SHOW VARIABLES like 'slow_query_log'
如果要开启慢查询日志,需要在 MySQL 的配置文件( /etc/my.cnf )中配置如下信息(linux版本的):
# 开启 MySQL 慢日志查询开关
slow_query_log = 1
# 设置慢日志的时间为 2 秒, SQL 语句执行时间超过 2 秒,就会视为慢查询,记录慢查询日志
long_query_time = 2

性能分析-profile

show profiles 能够在做 SQL 优化时帮助我们了解时间都耗费到哪里去了。通过 have_profiling
参数,能够看到当前 MySQL 是否支持 profile 操作:
SELECT @@have_profiling ;
可以看到,当前 MySQL 是支持 profile 操作的,但是开关是关闭的。可以通过 set 语句在
session/global 级别开启 profiling
SET profiling = 1;
开关已经打开了,接下来,我们所执行的 SQL 语句,都会被 MySQL 记录,并记录执行时间消耗到哪儿去
了。 我们直接执行如下的 SQL 语句:
select * from tb_user;
select * from tb_user where id = 1 ;
select * from tb_user where name = ' 白起 ' ;
select count (*) from tb_sku;
执行一系列的业务 SQL 的操作,然后通过如下指令查看指令的执行耗时:
-- 查看每一条 SQL 的耗时基本情况
show profiles;
-- 查看指定 query_id SQL 语句各个阶段的耗时情况
show profile for query query_id;
-- 查看指定 query_id SQL 语句 CPU 的使用情况
show profile cpu for query query_id;
查看每一条 SQL的耗时情况:
查看指定 SQL各个阶段的耗时情况 :

性能分析-explain

EXPLAIN 或者 DESC 命令获取 MySQL 如何执行 SELECT 语句的信息,包括在 SELECT 语句执行
过程中表如何连接和连接的顺序。
语法 :
-- 直接在 select 语句之前加上关键字 explain / desc
EXPLAIN SELECT 字段列表 FROM 表名 WHERE 条件 ;
Explain 执行计划中各个字段的含义:

17.索引使用-验证索引效率

在讲解索引的使用原则之前,先通过一个简单的案例,来验证一下索引,看看是否能够通过索引来提升
数据查询性能。在演示的时候,我们还是使用之前准备的一张表 tb_sku , 在这张表中准备了 1000w
的记录。
这张表中 id 为主键,有主键索引,而其他字段是没有建立索引的。 我们先来查询其中的一条记录,看
看里面的字段情况,执行如下 SQL
select * from tb_sku where id = 1\G;
#1/G:单纯的为了数据展示好看一点
可以看到即使有 1000w 的数据 , 根据 id 进行数据查询 , 性能依然很快,因为主键 id 是有索引的。 那么接
下来,我们再来根据 sn 字段进行查询,执行如下 SQL
SELECT * FROM tb_sku WHERE sn = '100000003145001' ;
我们可以看到根据 sn 字段进行查询,查询返回了一条数据,结果耗时 20.78sec ,就是因为 sn 没有索
引,而造成查询效率很低。
那么我们可以针对于 sn 字段,建立一个索引,建立了索引之后,我们再次根据 sn 进行查询,再来看一
下查询耗时情况。
创建索引:
create index idx_sku_sn on tb_sku(sn) ;
然后再次执行相同的 SQL 语句,再次查看 SQL 的耗时。
SELECT * FROM tb_sku WHERE sn = '100000003145001' ;
我们明显会看到, sn 字段建立了索引之后,查询性能大大提升。建立索引前后,查询耗时都不是一个数量级的。

18.最左前缀法则

如果索引了多列(联合索引),要遵守最左前缀法则。最左前缀法则指的是查询从索引的最左列开始,
并且不跳过索引中的列。如果跳跃某一列,索引将会部分失效 ( 后面的字段索引失效 )
tb_user 表为例,我们先来查看一下之前 tb_user 表所创建的索引。
tb_user 表中,有一个联合索引,这个联合索引涉及到三个字段,顺序分别为: profession
age status
对于最左前缀法则指的是,查询时,最左变的列,也就是 profession 必须存在,否则索引全部失效。
而且中间不能跳过某一列,否则该列后面的字段索引将失效。 接下来,我们来演示几组案例,看一下
具体的执行计划:
explain select * from tb_user where profession = ' 软件工程 ' and age = 31 and status
= '0';
explain select * from tb_user where profession = ' 软件工程 ' and age = 31;
explain select * from tb_user where profession = ' 软件工程 ';
以上的这三组测试中,我们发现只要联合索引最左边的字段 profession 存在,索引就会生效,只不
过索引的长度不同。 而且由以上三组测试,我们也可以推测出 profession 字段索引长度为 47 age
字段索引长度为 2 status 字段索引长度为 5
explain select * from tb_user where age = 31 and status = '0';
explain select * from tb_user where status = '0';
而通过上面的这两组测试,我们也可以看到索引并未生效,原因是因为不满足最左前缀法则,联合索引
最左边的列 profession 不存在。
explain select * from tb_user where profession = ' 软件工程 ' and status = '0';
上述的 SQL 查询时,存在 profession 字段,最左边的列是存在的,索引满足最左前缀法则的基本条
件。但是查询时,跳过了 age 这个列,所以后面的列索引是不会使用的,也就是索引部分生效,所以索
引的长度就是 47
思考题:
当执行 SQL 语句 : explain select * from tb_user where age = 31 and
status = '0' and profession = ' 软件工程 ' ; 时,是否满足最左前缀法则,走不走
上述的联合索引,索引长度?
可以看到,是完全满足最左前缀法则的,索引长度 54 ,联合索引是生效的。
注意 : 最左前缀法则中指的最左边的列,是指在查询时,联合索引的最左边的字段 ( 即是
第一个字段 ) 必须存在,与我们编写 SQL 时,条件编写的先后顺序无关。

19.索引失效

联合索引中,出现范围查询(>,<),范围查询右侧的列索引失效。

explain select * from tb_user where profession = ' 软件工程 ' and age > 30 and status
= '0';
当范围查询使用 > < 时,走联合索引了,但是索引的长度为 49 ,就说明范围查询右边的 status
段是没有走索引的。
explain select * from tb_user where profession = ' 软件工程 ' and age >= 30 and
status = '0';
当范围查询使用 >= <= 时,走联合索引了,但是索引的长度为 54 ,就说明所有的字段都是走索引
的。
所以,在业务允许的情况下,尽可能的使用类似于 >= <= 这类的范围查询,而避免使用 > <

索引列运算

不要在索引列上进行运算操作, 索引将失效。
tb_user 表中,除了前面介绍的联合索引之外,还有一个索引,是phone字段的单列索引。
A. 当根据 phone 字段进行等值匹配查询时 , 索引生效。
explain select * from tb_user where phone = '17799990015' ;
B. 当根据 phone 字段进行函数运算操作之后,索引失效。
explain select * from tb_user where substring(phone, 10 , 2 ) = '15' ;
字符串不加引号
字符串类型字段使用时,不加引号,索引将失效。
接下来,我们通过两组示例,来看看对于字符串类型的字段,加单引号与不加单引号的区别:
explain select * from tb_user where profession = ' 软件工程 ' and age = 31 and status
= '0' ;
explain select * from tb_user where profession = ' 软件工程 ' and age = 31 and status
= 0 ;
explain select * from tb_user where phone = '17799990015';
explain select * from tb_user where phone = 17799990015;
经过上面两组示例,我们会明显的发现,如果字符串不加单引号,对于查询结果,没什么影响,但是数 据库存在隐式类型转换,索引将失效。

模糊查询

如果仅仅是尾部模糊匹配,索引不会失效。如果是头部模糊匹配,索引失效。
接下来,我们来看一下这三条 SQL 语句的执行效果,查看一下其执行计划:
由于下面查询语句中,都是根据 profession 字段查询,符合最左前缀法则,联合索引是可以生效的,
我们主要看一下,模糊查询时, % 加在关键字之前,和加在关键字之后的影响。
explain select * from tb_user where profession like ' 软件 %' ;
explain select * from tb_user where profession like '% 工程 ' ;
explain select * from tb_user where profession like '% %' ;
经过上述的测试,我们发现,在 like 模糊查询中,在关键字后面加 % ,索引可以生效。而如果在关键字前面加了% ,索引将会失效。

or连接条件

or 分割开的条件, 如果 or 前的条件中的列有索引,而后面的列中没有索引,那么涉及的索引都不会被用到。
explain select * from tb_user where id = 10 or age = 23 ;
explain select * from tb_user where phone = '17799990017' or age = 23 ;
由于 age 没有索引,所以即使 id phone 有索引,索引也会失效。所以需要针对于 age 也要建立索引。然后,我们可以对age 字段建立索引。
create index idx_user_age on tb_user(age);
建立了索引之后,我们再次执行上述的 SQL 语句,看看前后执行计划的变化。
最终,我们发现,当 or 连接的条件,左右两侧字段都有索引时,索引才会生效。

数据分布影响

如果 MySQL 评估使用索引比全表更慢,则不使用索引。
select * from tb_user where phone >= '17799990005' ;
select * from tb_user where phone >= '17799990015' ;
经过测试我们发现,相同的 SQL 语句,只是传入的字段值不同,最终的执行计划也完全不一样,这是为 什么呢? 就是因为MySQL 在查询时,会评估使用索引的效率与走全表扫描的效率,如果走全表扫描更快,则放弃 索引,走全表扫描。 因为索引是用来索引少量数据的,如果通过索引查询返回大批量的数据,则还不如走全表扫描来的快,此时索引就会失效。
接下来,我们再来看看 is null is not null 操作是否走索引。
执行如下两条语句 :
explain select * from tb_user where profession is null ;
explain select * from tb_user where profession is not null ;
接下来,我们做一个操作将 profession 字段值全部更新为 null
然后,再次执行上述的两条 SQL ,查看SQL语句的执行计划。
最终我们看到,一模一样的 SQL 语句,先后执行了两次,结果查询计划是不一样的,为什么会出现这种
现象,这是和数据库的数据分布有关系。查询时 MySQL 会评估,走索引快,还是全表扫描快,如果全表
扫描更快,则放弃索引走全表扫描。 因此, is null is not null 是否走索引,得具体情况具体
分析,并不是固定的。

20.SQL提示(使用或者不用哪个索引)

目前 tb_user表的数据情况如下:
索引情况如下:
把上述的 idx_user_age, idx_email 这两个之前测试使用过的索引直接删除。
drop index idx_user_age on tb_user;
drop index idx_email on tb_user;
A. 执行 SQL : explain select * from tb_user where profession = ' 软件工程 ';
查询走了联合索引。
B. 执行 SQL ,创建 profession 的单列索引: create index idx_user_pro on
tb_user(profession);
C. 创建单列索引后,再次执行 A 中的SQL语句,查看执行计划,看看到底走哪个索引。
测试结果,我们可以看到, possible_keys idx_user_pro_age_sta,idx_user_pro 这两个
索引都可能用到,最终 MySQL 选择了 idx_user_pro_age_sta 索引。这是 MySQL 自动选择的结果。
那么,我们能不能在查询的时候,自己来指定使用哪个索引呢? 答案是肯定的,此时就可以借助于
MySQL SQL 提示来完成。 接下来,介绍一下 SQL 提示。
SQL 提示,是优化数据库的一个重要手段,简单来说,就是在 SQL 语句中加入一些人为的提示来达到优
化操作的目的。
1). use index : 建议 MySQL 使用哪一个索引完成此次查询(仅仅是建议, mysql 内部还会再次进
行评估)。
explain select * from tb_user use index(idx_user_pro) where profession = ' 软件工程' ;
2). ignore index : 忽略指定的索引。
explain select * from tb_user ignore index(idx_user_pro) where profession = ' 软件工程' ;
3). force index : 强制使用索引。
explain select * from tb_user force index(idx_user_pro) where profession = ' 软件工程' ;
示例演示:
A. use index
explain select * from tb_user use index(idx_user_pro) where profession = ' 软件工程' ;
B. ignore index
explain select * from tb_user ignore index(idx_user_pro) where profession = ' 软件工程' ;
C. force index
explain select * from tb_user force index(idx_user_pro_age_sta) where profession =
' 软件工程 ' ;

21.覆盖索引

尽量使用覆盖索引,减少 select * 。 那么什么是覆盖索引呢? 覆盖索引是指 查询使用了索引,并
且需要返回的列,在该索引中已经全部能够找到 。
接下来,我们来看一组 SQL 的执行计划,看看执行计划的差别,然后再来具体做一个解析。
explain select id, profession from tb_user where profession = ' 软件工程 ' and age =
31 and status = '0' ;
explain select id,profession,age, status from tb_user where profession = ' 软件工程 '
and age = 31 and status = '0' ;
explain select id,profession,age, status, name from tb_user where profession = '
件工程 ' and age = 31 and status = '0' ;
explain select * from tb_user where profession = ' 软件工程 ' and age = 31 and status
= '0' ;
上述这几条 SQL的执行结果为:
从上述的执行计划我们可以看到,这四条 SQL 语句的执行计划前面所有的指标都是一样的,看不出来差
异。但是此时,我们主要关注的是后面的 Extra ,前面两天 SQL 的结果为 Using where; Using
Index ; 而后面两条 SQL 的结果为: Using index condition 。
因为,在 tb_user 表中有一个联合索引 idx_user_pro_age_sta ,该索引关联了三个字段
profession age status ,而这个索引也是一个二级索引,所以叶子节点下面挂的是这一行的主
id 。 所以当我们查询返回的数据在 id profession age status 之中,则直接走二级索引
直接返回数据了。 如果超出这个范围,就需要拿到主键 id ,再去扫描聚集索引,再获取额外的数据
了,这个过程就是回表。 而我们如果一直使用 select * 查询返回所有字段值,很容易就会造成回表
查询(除非是根据主键查询,此时只会扫描聚集索引)。
为了大家更清楚的理解,什么是覆盖索引,什么是回表查询,我们一起再来看下面的这组 SQL 的执行过
程。
A. 表结构及索引示意图:
id 是主键,是一个聚集索引。 name 字段建立了普通索引,是一个二级索引(辅助索引)。
B. 执行SQL : select * from tb_user where id = 2;
根据 id 查询,直接走聚集索引查询,一次索引扫描,直接返回数据,性能高。
C. 执行 SQL:selet id,name from tb_user where name = 'Arm';
虽然是根据 name 字段查询,查询二级索引,但是由于查询返回在字段为 id name ,在 name 的二级索
引中,这两个值都是可以直接获取到的,因为覆盖索引,所以不需要回表查询,性能高。
D. 执行 SQL:selet id,name,gender from tb_user where name = 'Arm';
由于在 name 的二级索引中,不包含 gender ,所以,需要两次索引扫描,也就是需要回表查询,性能相
对较差一点。
思考题:
一张表 , 有四个字段 (id, username, password, status), 由于数据量大 , 需要对
以下 SQL 语句进行优化 , 该如何进行才是最优方案 :
select id,username,password from tb_user where username =
'itcast';
答案 : 针对于 username, password 建立联合索引 , sql : create index
idx_user_name_pass on tb_user(username,password);
这样可以避免上述的 SQL 语句,在查询的过程中,出现回表查询。

22.前缀索引

当字段类型为字符串( varchar text longtext 等)时,有时候需要索引很长的字符串,这会让
索引变得很大,查询时,浪费大量的磁盘 IO , 影响查询效率。此时可以只将字符串的一部分前缀,建立索引,这样可以大大节约索引空间,从而提高索引效率。
1). 语法
create index idx_xxxx on table_name(column(n)) ;
示例 :
tb_user 表的 email 字段,建立长度为 5 的前缀索引。
create index idx_email_5 on tb_user(email( 5 ));
2). 前缀长度
可以根据索引的选择性来决定,而选择性是指不重复的索引值(基数)和数据表的记录总数的比值,
索引选择性越高则查询效率越高, 唯一索引的选择性是 1 ,这是最好的索引选择性,性能也是最好的。
select count ( distinct email) / count (*) from tb_user ;
select count ( distinct substring(email, 1 , 5 )) / count (*) from tb_user ;
3). 前缀索引的查询流程
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值