search
HomeDatabaseMysql TutorialShare a SQL statement optimization experience

The database I use is mysql5.6. Here is a brief introduction to the scenario
Course schedule

create table Course(
c_id int PRIMARY KEY,
name varchar(10)
)

100 data items

Student table:

create table Student(
id int PRIMARY KEY,
name varchar(10)
)

data 70000 entries

Student Score Table SC

CREATE table SC(
sc_id int PRIMARY KEY,
s_id int,
c_id int,
score int
)

Data 70w entries

Purpose of query:

Find candidates who scored 100 points in the Chinese Language Test

Query statement:

select s.* from Student s where s.s_id in (select s_id from SC sc where sc.c_id = 0 and sc.score = 100 )

Execution time: 30248.271s

Halo, why is it so slow? Let’s check the query plan first:

EXPLAIN
select s.* from Student s where s.s_id in (select s_id from SC sc where sc.c_id = 0 and sc.score = 100 )

It is found that no index is used, and the type is ALL, so the first thing that comes to mind is to create an index. The fields to be indexed are of course the fields in the where condition.

First create an index for the c_id and score of the sc table

CREATE index sc_c_id_index on SC(c_id);
CREATE index sc_score_index on SC(score);

Execute the above query statement again, the time is: 1.054s

It is more than 30,000 times faster, greatly shortened Query time, it seems that indexes can greatly improve query efficiency. It is necessary to build indexes. Many times, we forget to build them

索引了,数据量小的的时候压根没感觉,这优化的感觉挺爽。

但是1s的时间还是太长了,还能进行优化吗,仔细看执行计划:

查看优化后的sql:

SELECT
 `YSB`.`s`.`s_id` AS `s_id`,
 `YSB`.`s`.`name` AS `name`
FROM
 `YSB`.`Student` `s`
WHERE
 < in_optimizer > (
 `YSB`.`s`.`s_id` ,< EXISTS > (
 SELECT
 1
 FROM
 `YSB`.`SC` `sc`
 WHERE
 (
 (`YSB`.`sc`.`c_id` = 0)
 AND (`YSB`.`sc`.`score` = 100)
 AND (
 < CACHE > (`YSB`.`s`.`s_id`) = `YSB`.`sc`.`s_id`
 )
 )
 )
 )

补充:这里有网友问怎么查看优化后的语句

方法如下:

在命令窗口执行

有type=all

按照我之前的想法,该sql的执行的顺序应该是先执行子查询

select s_id from SC sc where sc.c_id = 0 and sc.score = 100

耗时:0.001s

得到如下结果:

然后再执行

select s.* from Student s where s.s_id in(7,29,5000)

耗时:0.001s

这样就是相当快了啊,Mysql竟然不是先执行里层的查询,而是将sql优化成了exists子句,并出现了EPENDENT SUBQUERY,

mysql是先执行外层查询,再执行里层的查询,这样就要循环70007*11=770077次。

那么改用连接查询呢?

SELECT s.* from
Student s
INNER JOIN SC sc
on sc.s_id = s.s_id
where sc.c_id=0 and sc.score=100

这里为了重新分析连接查询的情况,先暂时删除索引sc_c_id_index,sc_score_index

执行时间是:0.057s

效率有所提高,看看执行计划:

这里有连表的情况出现,我猜想是不是要给sc表的s_id建立个索引

CREATE index sc_s_id_index on SC(s_id);
show index from SC

在执行连接查询

时间: 1.076s,竟然时间还变长了,什么原因?查看执行计划:

优化后的查询语句为:

SELECT
 `YSB`.`s`.`s_id` AS `s_id`,
 `YSB`.`s`.`name` AS `name`
FROM
 `YSB`.`Student` `s`
JOIN `YSB`.`SC` `sc`
WHERE
 (
 (
 `YSB`.`sc`.`s_id` = `YSB`.`s`.`s_id`
 )
 AND (`YSB`.`sc`.`score` = 100)
 AND (`YSB`.`sc`.`c_id` = 0)
 )

貌似是先做的连接查询,再进行的where条件过滤

回到前面的执行计划:

这里是先做的where条件过滤,再做连表,执行计划还不是固定的,那么我们先看下标准的sql执行顺序:

正常情况下是先join再where过滤,但是我们这里的情况,如果先join,将会有70w条数据发送join做操,因此先执行where

过滤是明智方案,现在为了排除mysql的查询优化,我自己写一条优化后的sql

SELECT
 s.*
FROM
 (
 SELECT
 *
 FROM
 SC sc
 WHERE
 sc.c_id = 0
 AND sc.score = 100
 ) t
INNER JOIN Student s ON t.s_id = s.s_id

即先执行sc表的过滤,再进行表连接,执行时间为:0.054s

和之前没有建s_id索引的时间差不多

查看执行计划:

先提取sc再连表,这样效率就高多了,现在的问题是提取sc的时候出现了扫描表,那么现在可以明确需要建立相关索引

CREATE index sc_c_id_index on SC(c_id);
CREATE index sc_score_index on SC(score);

再执行查询:

SELECT
 s.*
FROM
 (
 SELECT
 *
 FROM
 SC sc
 WHERE
 sc.c_id = 0
 AND sc.score = 100
 ) t
INNER JOIN Student s ON t.s_id = s.s_id

执行时间为:0.001s,这个时间相当靠谱,快了50倍

执行计划:

我们会看到,先提取sc,再连表,都用到了索引。

那么再来执行下sql

SELECT s.* from
Student s
INNER JOIN SC sc
on sc.s_id = s.s_id
where sc.c_id=0 and sc.score=100

执行时间0.001s

执行计划:

这里是mysql进行了查询语句优化,先执行了where过滤,再执行连接操作,且都用到了索引。

总结:

1.mysql嵌套子查询效率确实比较低

2.可以将其优化成连接查询

3.连接表时,可以先用where条件对表进行过滤,然后做表连接

(虽然mysql会对连表语句做优化)

4.建立合适的索引

5.学会分析sql执行计划,mysql会对sql进行优化,所以分析执行计划很重要

索引优化

上面讲到子查询的优化,以及如何建立索引,而且在多个字段索引时,分别对字段建立了单个索引

后面发现其实建立联合索引效率会更高,尤其是在数据量较大,单个列区分度不高的情况下。

单列索引

查询语句如下:

select * from user_test_copy where sex = 2 and type = 2 and age = 10

索引:

CREATE index user_test_index_sex on user_test_copy(sex);
CREATE index user_test_index_type on user_test_copy(type);
CREATE index user_test_index_age on user_test_copy(age);

分别对sex,type,age字段做了索引,数据量为300w,查询时间:0.415s

执行计划:

Share a SQL statement optimization experience

发现type=index_merge

这是mysql对多个单列索引的优化,对结果集采用intersect并集操作

多列索引

我们可以在这3个列上建立多列索引,将表copy一份以便做测试

create index user_test_index_sex_type_age on user_test(sex,type,age);

查询语句:

select * from user_test where sex = 2 and type = 2 and age = 10

执行时间:0.032s,快了10多倍,且多列索引的区分度越高,提高的速度也越多

执行计划:

Share a SQL statement optimization experience

最左前缀

多列索引还有最左前缀的特性:

执行一下语句:

select * from user_test where sex = 2
select * from user_test where sex = 2 and type = 2
select * from user_test where sex = 2 and age = 10

都会使用到索引,即索引的第一个字段sex要出现在where条件中

索引覆盖

就是查询的列都建立了索引,这样在获取结果集的时候不用再去磁盘获取其它列的数据,直接返回索引数据即可

如:

select sex,type,age from user_test where sex = 2 and type = 2 and age = 10

执行时间:0.003s

要比取所有字段快的多

排序

select * from user_test where sex = 2 and type = 2 ORDER BY user_name

时间:0.139s

在排序字段上建立索引会提高排序的效率

create index user_name_index on user_test(user_name)

最后附上一些sql调优的总结,以后有时间再深入研究

1. 列类型尽量定义成数值类型,且长度尽可能短,如主键和外键,类型字段等等

2. 建立单列索引

3. 根据需要建立多列联合索引

当单个列过滤之后还有很多数据,那么索引的效率将会比较低,即列的区分度较低,

那么如果在多个列上建立索引,那么多个列的区分度就大多了,将会有显著的效率提高。

4. Create a covering index based on the business scenario

Only query the fields required by the business. If these fields are covered by the index, the query efficiency will be greatly improved

5. Multi-table connection Indexes need to be established on fields

This can greatly improve the efficiency of table connections

6. Indexes need to be established on where condition fields

7. Indexes need to be established on sorting fields

8. An index needs to be created on the grouping field

9. Do not use arithmetic functions on the Where condition to avoid index failure

The above is the detailed content of Share a SQL statement optimization experience. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
图文详解mysql架构原理图文详解mysql架构原理May 17, 2022 pm 05:54 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于架构原理的相关内容,MySQL Server架构自顶向下大致可以分网络连接层、服务层、存储引擎层和系统文件层,下面一起来看一下,希望对大家有帮助。

mysql怎么替换换行符mysql怎么替换换行符Apr 18, 2022 pm 03:14 PM

在mysql中,可以利用char()和REPLACE()函数来替换换行符;REPLACE()函数可以用新字符串替换列中的换行符,而换行符可使用“char(13)”来表示,语法为“replace(字段名,char(13),'新字符串') ”。

mysql怎么去掉第一个字符mysql怎么去掉第一个字符May 19, 2022 am 10:21 AM

方法:1、利用right函数,语法为“update 表名 set 指定字段 = right(指定字段, length(指定字段)-1)...”;2、利用substring函数,语法为“select substring(指定字段,2)..”。

mysql的msi与zip版本有什么区别mysql的msi与zip版本有什么区别May 16, 2022 pm 04:33 PM

mysql的msi与zip版本的区别:1、zip包含的安装程序是一种主动安装,而msi包含的是被installer所用的安装文件以提交请求的方式安装;2、zip是一种数据压缩和文档存储的文件格式,msi是微软格式的安装包。

mysql怎么将varchar转换为int类型mysql怎么将varchar转换为int类型May 12, 2022 pm 04:51 PM

转换方法:1、利用cast函数,语法“select * from 表名 order by cast(字段名 as SIGNED)”;2、利用“select * from 表名 order by CONVERT(字段名,SIGNED)”语句。

MySQL复制技术之异步复制和半同步复制MySQL复制技术之异步复制和半同步复制Apr 25, 2022 pm 07:21 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于MySQL复制技术的相关问题,包括了异步复制、半同步复制等等内容,下面一起来看一下,希望对大家有帮助。

带你把MySQL索引吃透了带你把MySQL索引吃透了Apr 22, 2022 am 11:48 AM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了mysql高级篇的一些问题,包括了索引是什么、索引底层实现等等问题,下面一起来看一下,希望对大家有帮助。

mysql怎么判断是否是数字类型mysql怎么判断是否是数字类型May 16, 2022 am 10:09 AM

在mysql中,可以利用REGEXP运算符判断数据是否是数字类型,语法为“String REGEXP '[^0-9.]'”;该运算符是正则表达式的缩写,若数据字符中含有数字时,返回的结果是true,反之返回的结果是false。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),