当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL多表链接查询核心优化

MySQL多表链接查询核心优化

2017年12月12日  | 移动技术网IT编程  | 我要评论

概述

在一般的项目开发中,对数据表的多表查询是必不可少的。而对于存在大量数据量的情况时(例如百万级数据量),我们就需要从数据库的各个方面来进行优化,本文就先从多表查询开始。其他优化操作,后续另外更新,敬请关注。

数据背景

现假设有一个中学学校,学校中的年级有一年级、二年级、三年级,每个年级有两个班级。分别为101、102、201、202、301、302.

现在我们要为这个学校建立一个考试成绩统计系统。为此,我们对数据库的设计画了如下er图:

根据er图,我们设计了数据表,结构如下:
class 班级表:

+------------+---------+------+-----+---------+----------------+
| field      | type    | null | key | default | extra          |
+------------+---------+------+-----+---------+----------------+
| id         | int(11) | no   | pri | null    | auto_increment |
| class_name | int(11) | no   |     | null    |              |
| master_id  | int(11) | yes  |     | null    |                |
| is_key     | int(11) | no   |     | null    |                   |
+------------+---------+------+-----+---------+----------------+

student 学生表:

+------------+-------------+------+-----+---------+----------------+
| field      | type        | null | key | default | extra          |
+------------+-------------+------+-----+---------+----------------+
| id         | int(11)     | no   | pri | null    | auto_increment |
| school_id  | int(11)     | no   |     | null    |                |
| name       | varchar(30) | no   |     | null    |                |
| sex        | int(11)     | no   |     | null    |                |
| age        | int(11)     | no   |     | null    |                |
| class_name | int(11)     | no   |     | null    |                |
+------------+-------------+------+-----+---------+----------------+

course 课程表:

+--------------+-------------+------+-----+---------+----------------+
| field        | type        | null | key | default | extra          |
+--------------+-------------+------+-----+---------+----------------+
| id           | int(11)     | no   | pri | null    | auto_increment |
| course_name  | varchar(10) | no   |     | null    |                |
| grade        | int(11)     | no   |     | null    |                |
| president_id | int(11)     | yes  |     | null    |                |
| is_neces     | int(11)     | no   |     | null    |                |
| credit       | int(11)     | no   |     | null    |                |
| class_name   | int(11)     | yes  |     | null    |                |
+--------------+-------------+------+-----+---------+----------------+

score 成绩表:

+-----------+---------+------+-----+---------+----------------+
| field     | type    | null | key | default | extra          |
+-----------+---------+------+-----+---------+----------------+
| id        | int(11) | no   | pri | null    | auto_increment |
| course_id | int(11) | no   |     | null    |                |
| school_id | int(11) | no   |     | null    |                |
| score     | int(11) | yes  |     | null    |                |
+-----------+---------+------+-----+---------+----------------+

注:关于本文的数据库数据大家可以在文章最下方的相关下载中获取。资源链接中有两个版本的数据库,school.sql为初始数据库,school_2.sql为优化后的数据库。

连接(join)简介

内连(inner join)

inner join 关键字在表中存在至少一个匹配时返回行。

我们也用下面的交集维恩图来描述内连操作:

上面的维恩图只是表达了一个有限制情况(即存在join on),而对于没有约束的情况下,其实就是一个笛卡尔积运算。

*注:**inner join 与 join 是相同的。一般情况下,在sql语句中可以省略*inner关键字。

左连接(left join)

left join 关键字从左表(table1)返回所有的行,即使右表(table2)中没有匹配。如果右表中没有匹配,则结果为 null。

使用维恩图描述内连操作:

对于上面结果为 null的这一条,通过对实际测试的数据表进行操作,得到如下的测试结果:

+------------+-------+
| class_name | name  |
+------------+-------+
|        202 | null  |
|        301 | bob   |
|        302 | alice |
+------------+-------+

右连接(right join)

right join 关键字从右表(table2)返回所有的行,即使左表(table1)中没有匹配。如果左表中没有匹配,则结果为 null。

注:右连接可以理解成左连接的对称互补,详细说明可参见左连接。

全连(full join)

full outer join 关键字只要左表(table1)和右表(table2)其中一个表中存在匹配,则返回行.

full outer join 关键字结合了 left join 和 right join 的结果。

联合(union)

union 操作符用于合并两个或多个 select 语句的结果集。

请注意,union 内部的每个 select 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每个 select 语句中的列的顺序必须相同。

mysql的join实现原理

在mysql 中,只有一种join 算法,就是大名鼎鼎的nested loop join,他没有其他很多数据库所提供的hash join,也没有sort merge join。顾名思义,nested loop join 实际上就是通过驱动表的结果集作为循环基础数据,然后一条一条的通过该结果集中的数据作为过滤条件到下一个表中查询数据,然后合并结果。如果还有第三个参与join,则再通过前两个表的join 结果集作为循环基础数据,再一次通过循环查询条件到第三个表中查询数据,如此往复。
                                       – 《mysql性能调优与架构设计》

多表查询实战

查询各个班级的班长姓名

优化分析

对于这个多表的查询使用where是可以很好地完成查询,而查询的结果从表面上看,完全没什么问题,如下:

+------------+---------+
| class_name | name    |
+------------+---------+
|        101 | william |
|        102 | peter   |
|        201 | judy    |
|        202 | polly   |
|        301 | grace   |
|        302 | sunny   |
+------------+---------+

可是,由于我们使用的是where,这个与内连接在有条件限制的情况下是一样的,其维恩图也可以一并参考。可是,如果现在我们假设,有一个新的班级303,或是这个303的班级暂时还没有班长。这个时候通过where就无法完成查询了。上面的结果中就已经很好地给出解释。

这个时候,我们就需要通过外连接中的左连接(如果采用右连接,那么相应的表位置也要进行替换)来进行查询了。在左连的查询中,因为是包含了”左表“的全部行,所以对于未选出班长的303来说,这个很有必要。采用左连操作的结果如下:

+------------+---------+
| class_name | name    |
+------------+---------+
|        101 | william |
|        102 | peter   |
|        201 | judy    |
|        202 | polly   |
|        301 | grace   |
|        302 | sunny   |
|        303 | null    |
+------------+---------+

sql展示

朴素的where

select cl.class_name, st.name
from class cl, student st
where cl.master_id=st.school_id;

inner join

select cl.class_name, st.name
from class cl
join student st
on cl.master_id=st.school_id;

leaf join

select cl.class_name, st.name
from class cl
left join student st
on cl.master_id=st.school_id;

right join

select cl.class_name, st.name
from student st
right join class cl
on cl.master_id=st.school_id;

利用 explain 检查优化器

通过explain我们分别检查上面where语句和left join的优化过程。结果如下:

where

+----+-------------+-------+------+---------------+------+---------+------+------+--------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | extra                          |
+----+-------------+-------+------+---------------+------+---------+------+------+--------------------------------+
|  1 | simple      | cl    | all  | null          | null | null    | null |    7 |                                |
|  1 | simple      | st    | all  | null          | null | null    | null |  301 | using where; using join buffer |
+----+-------------+-------+------+---------------+------+---------+------+------+--------------------------------+

left join

+----+-------------+-------+------+---------------+------+---------+------+------+-------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
|  1 | simple      | cl    | all  | null          | null | null    | null |    7 |       |
|  1 | simple      | st    | all  | null          | null | null    | null |  301 |       |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+

对于上面的两个结果,我们可以看到有一个很明显的区别在于extra。

using where说明进行了where的过滤操作,using join buffer说明进行join缓存。

从上面的结果中,还可以看到每种情况的两种查询操作都是经过了全表扫描。而这对于大量数据而言是很不利的。

现在,我们可以为被驱动表的join字段添加索引,再对其进行explain检查。

添加索引

alter table student add index index_school_id (school_id);

通过explain我们分别检查上面where语句和left join的优化过程。结果如下:

where

+----+-------------+-------+------+-----------------+-----------------+---------+---------------------+------+-------+
| id | select_type | table | type | possible_keys   | key             | key_len | ref                 | rows | extra |
+----+-------------+-------+------+-----------------+-----------------+---------+---------------------+------+-------+
|  1 | simple      | cl    | all  | null            | null            | null    | null                |    7 |       |
|  1 | simple      | st    | ref  | index_school_id | index_school_id | 4       | school.cl.master_id |    1 |       |
+----+-------------+-------+------+-----------------+-----------------+---------+---------------------+------+-------+

left join

+----+-------------+-------+------+-----------------+-----------------+---------+---------------------+------+-------+
| id | select_type | table | type | possible_keys   | key             | key_len | ref                 | rows | extra |
+----+-------------+-------+------+-----------------+-----------------+---------+---------------------+------+-------+
|  1 | simple      | cl    | all  | null            | null            | null    | null                |    7 |       |
|  1 | simple      | st    | ref  | index_school_id | index_school_id | 4       | school.cl.master_id |    1 |       |
+----+-------------+-------+------+-----------------+-----------------+---------+---------------------+------+-------+

现在,可以很明显地看出rows列的数值,在被驱动表处都是1,这大降低了查询的复杂度。而且对于type列,也从一开始的all变成了现在的ref。还有一些其他的列也被修改了。

查询番外

根据学号查询一个学生的成绩单

where 查询

explain select st.name, co.course_name, sc.score
from student st, score sc, course co
where sc.school_id=st.school_id
and co.id=sc.course_id
and st.school_id=100005;

join 查询

explain select st.name, co.course_name, sc.score
from student st
join score sc on sc.school_id=st.school_id
join course co on co.id=sc.course_id
where st.school_id=100005;

结果

+----+-------------+-------+--------+---------------------------------------+--------------------+---------+---------------------+------+-------+
| id | select_type | table | type   | possible_keys                         | key                | key_len | ref                 | rows | extra |
+----+-------------+-------+--------+---------------------------------------+--------------------+---------+---------------------+------+-------+
|  1 | simple      | st    | ref    | index_school_id                       | index_school_id    | 4       | const               |    1 |       |
|  1 | simple      | sc    | ref    | index_school_id_sc,index_course_id_sc | index_school_id_sc | 4       | const               |    3 |       |
|  1 | simple      | co    | eq_ref | primary                               | primary            | 4       | school.sc.course_id |    1 |       |
+----+-------------+-------+--------+---------------------------------------+--------------------+---------+---------------------+------+-------+

优化总结

  • 对于要求全面的结果时,我们需要使用连接操作(left join / right join / full join);
  • 不要以为使用mysql的一些连接操作对查询有多么大的改善,核心是索引;
  • 对被驱动表的join字段添加索引;

sql语句表

创建数据库

create database school;

创建数据表

学生表

create table student(
id int not null auto_increment, /* 学生表id */
school_id int(11) not null, /* 学号 */
name varchar(30) not null, /* 姓名 */
sex int not null, /* 性别 */
age int not null, /* 年龄 */
class_name int not null, /* 班级名称 */
primary key (id) /* 学生表主键 */
);
insert into student(school_id, name, sex, age, class_name) values(100005, 'bob', 1, 17, 301);

班级表

create table class(
id int not null auto_increment, /* 班级表id */
class_name int not null, /* 班级名称 */
master_id int, /* 班长id */
is_key int not null, /* 是否重点班级 */
primary key (id) /* 班级表主键 */
);
insert into class(class_name, master_id, is_key) values(301, 100001, 1);

课程表

create table course(
id int not null auto_increment, /* 课程表id */
course_name varchar(10) not null, /* 课程名称 */
grade int not null, /* 当前课程所属年级 */
president_id int, /* 课代表id */
is_neces int not null, /* 是否必修课 */
credit int not null, /* 学分 */
primary key (id) /* 课程表主键 */
);
insert into course(course_name, grade, president_id, is_neces, credit) values('math', 3, 100214, 1, 4);
alter table course add column class_name int;

成绩表

create table score(
id int not null auto_increment, /* 成绩表id */
course_id int not null, /* 课程id */
school_id int not null, /* 学号 */
score int, /* 考试成绩 */
primary key (id) /* 成绩表主键 */
);
insert into score(course_id, school_id, score) values(1, 100005, 88);

导入导出

/* 导出数据库 */
mysqldump -u root -p school > f:/data/mysql/school.sql
/* 导入数据库 */
source /root/upload/school.sql;

索引操作

/* 添加索引 */
alter table class add index index_master_id (master_id);
/* 删除索引 */
drop index index_name on talbe_name;

查询实战

查询所有课程名称

select course_name from course group by course_name;

查询一个学生全部课程

/* 子查询 */
select course_name from course where id in (select course_id from score where school_id=100005);

统计每个班级有多少学生

select class_name, count(*) from student group by class_name;

根据学号查询一个学生的成绩单

/* where */
select st.name, co.course_name, sc.score
from student st, score sc, course co
where sc.school_id=st.school_id
and co.id=sc.course_id
and st.school_id=100005;
/* join */
select st.name, co.course_name, sc.score
from student st
join score sc on sc.school_id=st.school_id
join course co on co.id=sc.course_id
and st.school_id=100005;

查询各个班级的班长姓名

/* where */
select cl.class_name, st.name
from class cl, student st
where cl.master_id=st.school_id;
/* 子查询 */
select st.class_name, st.name
from student st
where st.school_id in
(select master_id from class);
/* join */
select cl.class_name, st.name
from class cl
join student st
on cl.master_id=st.school_id;
/* left join */
select cl.class_name, st.name
from class cl
left join student st
on cl.master_id=st.school_id;
/* right join */
select cl.class_name, st.name
from student st
right join class cl
on cl.master_id=st.school_id;

其他查询

select name, class_name from student group by class_name
union all
select id, class_name from class;

原文链接:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网