Table of Contents
索引优化
单列索引
多列索引
索引覆盖
排序
Home Database Mysql Tutorial Share a SQL statement optimization experience

Share a SQL statement optimization experience

Apr 05, 2017 am 11:37 AM

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)
)
Copy after login

100 data items

Student table:

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

data 70000 entries

Student Score Table SC

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

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 )
Copy after login

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 )
Copy after login

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);
Copy after login
Copy after login

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`
 )
 )
 )
 )
Copy after login

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

方法如下:

在命令窗口执行

有type=all

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

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

耗时:0.001s

得到如下结果:

然后再执行

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

耗时: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
Copy after login
Copy after login

这里为了重新分析连接查询的情况,先暂时删除索引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
Copy after login

在执行连接查询

时间: 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)
 )
Copy after login

貌似是先做的连接查询,再进行的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
Copy after login
Copy after login

即先执行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);
Copy after login
Copy after login

再执行查询:

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
Copy after login
Copy after login

执行时间为: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
Copy after login
Copy after login

执行时间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
Copy after login

索引:

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);
Copy after login

分别对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);
Copy after login

查询语句:

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

执行时间: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
Copy after login

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

索引覆盖

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

如:

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

执行时间:0.003s

要比取所有字段快的多

排序

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

时间:0.139s

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

create index user_name_index on user_test(user_name)
Copy after login

最后附上一些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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles