百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

关于mysql的innodb 800w+数据不带条件count性能优化的思考

wptr33 2024-12-28 15:58 17 浏览

关于mysql的innodb 800w+数据不带条件count性能优化的思考

1、查看mysql版本

mysql> show variables like '%version%';
+-------------------------+------------------------------+
| Variable_name           | Value                        |
+-------------------------+------------------------------+
| innodb_version          | 5.7.32                       |
| protocol_version        | 10                           |
| slave_type_conversions  |                              |
| tls_version             | TLSv1,TLSv1.1,TLSv1.2        |
| version                 | 5.7.32                       |
| version_comment         | MySQL Community Server (GPL) |
| version_compile_machine | x86_64                       |
| version_compile_os      | Win64                        |
+-------------------------+------------------------------+

2、建表并初始化数据

2.1、建表语句如下

mysql> desc user;
mysql> show create table user;

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `birthday` date NOT NULL,
  `no` int(11) NOT NULL DEFAULT '0',
  `remark` varchar(255) NOT NULL,
  `modify_date` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
  `create_date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

2.2、初始化500w+数据

insert into user(name,birthday,no,remark,modify_date,create_date) values("test-user-name",'2000-01-01',0,"测试count性能",'2019-01-01','2019-01-01');

反复执行以下语句直至数据量超过500w+
insert into user(name,birthday,no,remark,modify_date,create_date) select name,birthday,no,remark,modify_date,create_date from user ;

执行一些更新操作
update user set no=id+1000000;

3、开启profiling参数并查看耗时

3.1、开启profiling参数

mysql> show variables like '%profiling%'; 查看配置情况
mysql> set profiling=1; 开启配置

3.2、查看count语句执行耗时

使用count(*)或count(1)耗时均超过4秒

mysql> select count(*) from user;
+----------+
| count(*) |
+----------+
|  8388608 |
+----------+

mysql> show profiles;
+----------+------------+-----------------------------------+
| Query_ID | Duration   | Query                             |
+----------+------------+-----------------------------------+
|        1 | 0.00172175 | show variables like '%profiling%' |
|        2 | 4.09369675 | select count(*) from user         |
+----------+------------+-----------------------------------+

mysql> show profile for query 2;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| starting             | 4.7E-5   |
| checking permissions | 4E-6     |
| Opening tables       | 1.4E-5   |
| init                 | 8E-6     |
| System lock          | 5E-6     |
| optimizing           | 3E-6     |
| statistics           | 9E-6     |
| preparing            | 7E-6     |
| executing            | 2E-6     |
| Sending data         | 4.093506 |
| end                  | 8E-6     |
| query end            | 2E-5     |
| closing tables       | 7E-6     |
| freeing items        | 4.8E-5   |
| cleaning up          | 9E-6     |
+----------------------+----------+

在user表没有辅助索引,仅有一个主键索引的情况下,可以看到耗时超过4秒

3.3、创建no字段的辅助索引再进行count统计

create index index_no on user(no);

3.4、查看当前索引情况

mysql> show index from user;

3.5、增加辅助索引后再次执行count可以看到查询速度有明显的提升

可通过show profiles查看最新的queryid,观察实际的耗时


4、通过explain执行计划分析一下有辅助索引和无辅助索引的区别

mysql> explain select count(*) from user;
+----+-------------+-------+------------+-------+---------------+----------+---------+------+---------+----------+-------------+
| id | select_type | table | partitions | type  | possible_keys | key      | key_len | ref  | rows    | filtered | Extra       |
+----+-------------+-------+------------+-------+---------------+----------+---------+------+---------+----------+-------------+
|  1 | SIMPLE      | user  | NULL       | index | NULL          | index_no | 4       | NULL | 8159175 |      100 | Using index |
+----+-------------+-------+------------+-------+---------------+----------+---------+------+---------+----------+-------------+
mysql> drop index index_no on user;
mysql> explain select count(*) from user;
+----+-------------+-------+------------+-------+---------------+---------+---------+------+---------+----------+-------------+
| id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref  | rows    | filtered | Extra       |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+---------+----------+-------------+
|  1 | SIMPLE      | user  | NULL       | index | NULL          | PRIMARY | 4       | NULL | 8159175 |      100 | Using index |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+---------+----------+-------------+

通过explain执行计划可以看到count统计查询在有辅助索引时,选择了走辅助索引,没有时选择了PRIMARY主键索引,从结果可以看到使用了主键索引反而比较慢,这是为什么呢?通常mysql普通的数据检索时主键索引会比普通索引快,原因是主键索引不需要回表,而count是什么原因会造成有如此大的差异呢?

5、继续通过optimizer trace跟踪优化器过程

5.1、查看optimizer_trace状态

mysql> show variables like '%optimizer_trace%';
+------------------------------+----------------------------------------------------------------------------+
| Variable_name                | Value                                                                      |
+------------------------------+----------------------------------------------------------------------------+
| optimizer_trace              | enabled=off,one_line=off                                                   |
| optimizer_trace_features     | greedy_search=on,range_optimizer=on,dynamic_range=on,repeated_subselect=on |
| optimizer_trace_limit        | 1                                                                          |
| optimizer_trace_max_mem_size | 16384                                                                      |
| optimizer_trace_offset       | -1                                                                         |
+------------------------------+----------------------------------------------------------------------------+

5.2、开启并查看执行情况

  • 开启optimizer_trace
mysql> show variables like '%optimizer_trace%'; 查看参数状态
mysql> set optimizer_trace="enabled=on";
mysql> set end_markers_in_json=on; 
  • 在有索引与无索引情况下执行count查询后均使用以下查询语句获取优化器优化过程
SELECT * FROM information_schema.OPTIMIZER_TRACE;

可以观察到在有辅助索引及无辅助索引index_no的两种情况下,优化器的执行过程一样,并没有差异,没有体现出性能的差异,不过在optimizer_trace结果中可以看到是scan;

            "considered_execution_plans": [
              {
                "plan_prefix": [
                ],
                "table": "`user`",
                "best_access_path": {
                  "considered_access_paths": [
                    {
                      "rows_to_scan": 8159175,
                      "access_type": "scan",
                      "resulting_rows": 8.16e6,
                      "cost": 1.67e6,
                      "chosen": true
                    }
                  ]
                },
                "condition_filtering_pct": 100,
                "rows_for_plan": 8.16e6,
                "cost_for_plan": 1.67e6,
                "chosen": true
              }
            ]

6、既然都是scan那应该就应该是和本身的结构有关了

6.1、聚簇索引(clustered index)和非聚簇索引(secondary index)的区别

innodb的clustered index是把primary key以及row data保存在一起的,而secondary index则是单独存放,然后有个指针指向primary key,所以二级索引树比主键索引树小。因此优化器基于成本的考虑,优先选择的是二级索引。

6.2、验证

  • 创建新表user_no仅保留idno字段
CREATE TABLE `user_no` (
  `id` int(10) unsigned NOT NULL,
  `no` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `index_no` (`no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  • 插入所有数据
insert into user_no select id,no from user

基于上面的结论,如果表的主键索引树与二级索引树差别不大的话应该可以获得相近的结果,默认count(*)时会选择二级索引(辅助索引)index_no,可以通过explain检查

mysql> explain select count(*) from user_no;
mysql> explain select count(*) from user_no force index(primary);
  • 开启profiling参数并执行统计,查看耗时的差异

将分别统计user表(此表无辅助索引)、user_no表的两种情况(默认走辅助索引index_no以及主键索引)

mysql> set profiling=1;
mysql> select count(*) from user_no;
mysql> select count(*) from user_no force index(primary);
mysql> show profiles;
+----------+------------+---------------------------------------------------+
| Query_ID | Duration   | Query                                             |
+----------+------------+---------------------------------------------------+
|        1 |   4.862296 | select count(*) from user                         |
|        2 |  1.8102375 | select count(*) from user_no                      |
|        3 | 1.98250375 | select count(*) from user_no force index(primary) |
+----------+------------+---------------------------------------------------+

可以看到当表user_no只剩下2个字段时,使用主键索引或辅助索引时略有差异但并不大,按照这个结论,尝试在大表(较多字段)中使用了like操作,同样能够得到不错的性能提升select id from user force index(index_name) where name like '%33D0EB9%' ;

不同的机器性能或不同的mysql版本可能表现不一样

相关推荐

【推荐】一款开源免费、美观实用的后台管理系统模版

如果您对源码&技术感兴趣,请点赞+收藏+转发+关注,大家的支持是我分享最大的动力!!!项目介绍...

Android架构组件-App架构指南,你还不收藏嘛

本指南适用于那些已经拥有开发Android应用基础知识的开发人员,现在想了解能够开发出更加健壮、优质的应用程序架构。首先需要说明的是:AndroidArchitectureComponents翻...

高德地图经纬度坐标批量拾取(高德地图批量查询经纬度)

使用方法在桌面上新建一个index.txt文件,把下面的代码复制进去保存,再把文件名改成index.html保存,双击运行打开即可...

flutter系列之:UI layout简介(flutter ui设计)

简介对于一个前端框架来说,除了各个组件之外,最重要的就是将这些组件进行连接的布局了。布局的英文名叫做layout,就是用来描述如何将组件进行摆放的一个约束。...

Android开发基础入门(一):UI与基础控件

Android基础入门前言:...

iOS的布局体系-流式布局MyFlowLayout

iOS布局体系的概览在我的CSDN博客中的几篇文章分别介绍MyLayout布局体系中的视图从一个方向依次排列的线性布局(MyLinearLayout)、视图层叠且停靠于父布局视图某个位置的框架布局(M...

TDesign企业级开源设计系统越发成熟稳定,支持 Vue3 / 小程序

TDesing发展越来越好了,出了好几套组件库,很成熟稳定了,新项目完全可以考虑使用。...

WinForm实现窗体自适应缩放(winform窗口缩放)

众所周知,...

winform项目——仿QQ即时通讯程序03:搭建登录界面

上两篇文章已经对CIM仿QQ即时通讯项目进行了需求分析和数据库设计。winform项目——仿QQ即时通讯程序01:原理及项目分析...

App自动化测试|原生app元素定位方法

元素定位方法介绍及应用Appium方法定位原生app元素...

61.C# TableLayoutPanel控件(c# tabcontrol)

摘要TableLayoutPanel在网格中排列内容,提供类似于HTML元素的功能。TableLayoutPanel控件允许你将控件放在网格布局中,而无需精确指定每个控件的位置。其单元格...

想要深入学习Android性能优化?看完这篇直接让你一步到位

...

12个python数据处理常用内置函数(python 的内置函数)

在python数据分析中,经常需要对字符串进行各种处理,例如拼接字符串、检索字符串等。下面我将对python中常用的内置字符串操作函数进行介绍。1.计算字符串的长度-len()函数str1='我爱py...

如何用Python程序将几十个PDF文件合并成一个PDF?其实只要这四步

假定你有一个很无聊的任务,需要将几十个PDF文件合并成一个PDF文件。每一个文件都有一个封面作为第一页,但你不希望合并后的文件中重复出现这些封面。即使有许多免费的程序可以合并PDF,很多也只是简单的将...

Python入门知识点总结,Python三大数据类型、数据结构、控制流

Python基础的重要性不言而喻,是每一个入门Python学习者所必备的知识点,作为Python入门,这部分知识点显得很庞杂,内容分支很多,大部分同学在刚刚学习时一头雾水。...