MySQL:通过增加索引进行SQL查询优化

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 【实验】一次非常有意思的SQL优化经历:从30248.271s到0.001s

【实验】

一次非常有意思的SQL优化经历:从30248.271s到0.001s

数据准备

1、新建3张数据表

-- 课程表 数据 100条
drop table course;
create table course(
id int primary key auto_increment,
name varchar(10)
);
-- 学生表 数据 7w条
create table student(
id int primary key auto_increment,
name varchar(10)
);
-- 学生成绩表 数据 700w条
create table student_score(
id int primary key auto_increment,
course_id int,
student_id int,
score int
);

2、使用脚本生成数据

# -*- coding: utf-8 -*-
"""
安装依赖包
pip install requests chinesename pythink pymysql
Windows 登陆mysql: winpty mysql -uroot -p
"""
import random
from chinesename import ChineseName
from pythink import ThinkDatabase
db_url = "mysql://root:123456@localhost:3306/demo?charset=utf8"
think_db = ThinkDatabase(db_url)
course_table = think_db.table("course")
student_table = think_db.table("student")
student_score_table = think_db.table("student_score")
# 准备课程数据
course_list = [{"name": "课程{}".format(i)} for i in range(100)]
ret = course_table.insert(course_list).execute()
print(ret)
# 准备学生数据
cn = ChineseName()
student_list = [{"name": name} for name in cn.getNameGenerator(70000)]
ret = student_table.insert(student_list).execute()
print(ret)
# 准备学生成绩
score_list = []
for i in range(1, 101):
    for j in range(1, 70001):
        item = {
            "course_id": i,
            "student_id": j,
            "score": random.randint(0, 100)
        }
        score_list.append(item)
ret = student_score_table.insert(score_list, truncate=20000).execute()
print(ret)
think_db.close()

3、检查数据情况

mysql> select * from  course limit 10;
+----+-------+
| id | name  |
+----+-------+
|  1 | 课程0    |
|  2 | 课程1    |
|  3 | 课程2    |
|  4 | 课程3    |
|  5 | 课程4    |
|  6 | 课程5    |
|  7 | 课程6    |
|  8 | 课程7    |
|  9 | 课程8    |
| 10 | 课程9    |
+----+-------+
10 rows in set (0.07 sec)
mysql> select * from student limit 10;
+----+--------+
| id | name   |
+----+--------+
|  1 | 司徒筑     |
|  2 | 窦侗      |
|  3 | 毕珊      |
|  4 | 余怠      |
|  5 | 喻献       |
|  6 | 庾莫      |
|  7 | 蒙煮       |
|  8 | 芮佰      |
|  9 | 鄢虹      |
| 10 | 毕纣       |
+----+--------+
10 rows in set (0.05 sec)
mysql> select * from student_score order by id desc limit 10;
+---------+-----------+------------+-------+
| id      | course_id | student_id | score |
+---------+-----------+------------+-------+
| 7000000 |       100 |      70000 |    24 |
| 6999999 |       100 |      69999 |    71 |
| 6999998 |       100 |      69998 |    33 |
| 6999997 |       100 |      69997 |    14 |
| 6999996 |       100 |      69996 |    97 |
| 6999995 |       100 |      69995 |    63 |
| 6999994 |       100 |      69994 |    35 |
| 6999993 |       100 |      69993 |    66 |
| 6999992 |       100 |      69992 |    58 |
| 6999991 |       100 |      69991 |    99 |
+---------+-----------+------------+-------+
10 rows in set (0.06 sec)

4、检查数据数量

mysql> select count(*) from student;
+----------+
| count(*) |
+----------+
|    70000 |
+----------+
1 row in set (0.02 sec)
mysql> select count(*) from course;
+----------+
| count(*) |
+----------+
|      100 |
+----------+
1 row in set (0.00 sec)
mysql> select count(*) from student_score;
+----------+
| count(*) |
+----------+
|  7000000 |
+----------+
1 row in set (4.08 sec)

优化测试

1、直接查询



select * from student 
where id in (
select student_id from student_score  where 
course_id=1 and score=100
);

不知道为什么 2.7s 就执行完了… 原文中说 执行时间:30248.271s


马上看了下版本号,难道是版本的问题:

我的 : Server version: 5.7.21
原文:mysql 5.6


用 explain 看执行计划 type=all

explain extended
select * from student 
where id in (
select student_id from student_score  where
course_id=1 and score=100
);
# 执行完上一句之后紧接着执行
mysql> show warnings;
SELECT
    `demo`.`student`.`id` AS `id`,
    `demo`.`student`.`name` AS `name` 
FROM
    `demo`.`student` semi
    JOIN ( `demo`.`student_score` ) 
WHERE
    (
        ( `<subquery2>`.`student_id` = `demo`.`student`.`id` ) 
        AND ( `demo`.`student_score`.`score` = 100 ) 
    AND ( `demo`.`student_score`.`course_id` = 1 ) 
    )

2、增加索引

单条大概执行15s

alter table student_score add index INDEX_COURSE_ID(course_id);
alter table student_score add index INDEX_SCORE(score);

加完索引之后执行 0.027s ,速度快了 100倍(2.7 / 0.027)


3、使用 inner join

用了 0.26

select s.id, s.name from student as s inner JOIN student_score as ss 
on s.id=ss.student_id 
where ss.course_id=1 and ss.score=100

4、再次优化

执行也是 0.26, 并没有像原文所说的那样 0.001s…难道他的机器比我好?

select s.id, s.name from 
(select * from student_score where course_id=1 and score=100 ) as t 
inner join student as s 
on s.id=t.student_id

虽然和原文很多不一致的地方,不过也算是一次加索引优化数据库查询的实际操作了


参考文章

一次非常有意思的SQL优化经历:从30248.271s到0.001s

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
3月前
|
关系型数据库 MySQL 数据库
提高查询效率:MySQL高级查询技巧
提高查询效率:MySQL高级查询技巧
41 0
|
5月前
|
SQL 关系型数据库 MySQL
MySQL -通过调整索引提升查询效率
MySQL -通过调整索引提升查询效率
MySQL -通过调整索引提升查询效率
|
6月前
|
SQL 关系型数据库 MySQL
MySQL 大表如何优化查询效率?
MySQL 大表如何优化查询效率?
78 0
|
7月前
|
SQL 关系型数据库 MySQL
深入解析MySQL视图、索引、数据导入导出:优化查询和提高效率
索引是一种特殊的数据库结构,由数据表中的一列或多列组合而成,可以用来快速查询数据表中有某一特定值的记录。通过索引,查询数据时不用读完记录的所有信息,而只是查询索引列。否则,数据库系统将读取每条记录的所有信息进行匹配。索引可以根据一个或多个列的值进行排序和搜索,提高查询时的效率。MySQL索引(Index)是一种特殊的数据结构,建立在表的列上,旨在加快数据库查询的速度通过在索引列上创建索引,数据库可以更快地定位和访问特定值,而无需扫描整个数据表。索引可以应用于单个列或多个列的组合,可以按升序或。
|
SQL 运维 监控
索引对MYSQL性能的影响
索引到底对性能有多少影响? 这个问题估计是很多MySQL小白好奇的问题。当然我也是一样。因为之前的时候,并没有对索引有太多的注意,而且之前的工作经历,因为数据量很小,索引所起到的作用并不是很大,所以也没有太大注意。
170 0
|
10月前
|
存储 SQL JSON
MySQL查询为什么选择使用这个索引?——基于MySQL 8.0.22索引成本计算
多个索引之中,MySQL为什么选择这个索引?本文带你进行计算分析
100 0
MySQL查询为什么选择使用这个索引?——基于MySQL 8.0.22索引成本计算
|
10月前
|
存储 SQL 关系型数据库
mysql中SQL查询优化方法总结
mysql中SQL查询优化方法总结
|
11月前
|
SQL 关系型数据库 MySQL
mysql如何优化索引
mysql如何优化索引
58 0
|
缓存 关系型数据库 MySQL
如何在MySQL中优化表性能?
如何在MySQL中优化表性能?
129 0
|
SQL 关系型数据库 MySQL
MySQL:通过增加索引进行SQL查询优化
【实验】 一次非常有意思的SQL优化经历:从30248.271s到0.001s
101 0