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: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 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

MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 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.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development 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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor