【案例】MySQL count操作优化案例一则

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介:
一 背景

 某业务的数据库定期报 thread_runing 飙高,通定位发现一个慢查询sql导致会话堆积。执行sql 耗时如下


root@db 05:32:05>select count(item_id) from xxxtable where selid = 345705650 and end_time > now();
 
+----------------+

| count(item_id) |

+----------------+

| 2247052 |

+----------------+

1 row in set (4.65 sec) 

二 分析   
慢查询表结构如下 


root@db >show create table xxxtable \G
 
*************************** 1. row ***************************

       Table: uac_shop_item_promotion_0091

Create Table: CREATE TABLE `uac_shop_item_promotion_0091` (

  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',

  `gmt_modified` datetime NOT NULL COMMENT '修改时间',

  `selid` bigint(20) NOT NULL COMMENT '分表字段',

  `end_time` datetime NOT NULL COMMENT '活动结束时间',

  `item_id` bigint(20) NOT NULL COMMENT '商品id',

  PRIMARY KEY (`id`),

  UNIQUE KEY `idx_uq_item` (`item_id`),

  KEY `idx_deller_id_end_time` (`selid`,`end_time`),

  KEY `idx_deller_id_start_time` (`selid`,`start_time`),

  KEY `idx_seller_item_start` (`selid`,`start_time`,`item_id`)

) ENGINE=InnoDB AUTO_INCREMENT=42132149 DEFAULT CHARSET=gbk COMMENT='索引表'

1 row in set (0.00 sec) 

很明显出现问题的sql由于使用了count(item_id) ,而item_id字段并没有和 selid 和end_time 构成有效索引  故该sql 没有合理的使用索引 。查看其直系计划


root@db >explain select count(item_id) from xxxtable 
 
        >where selid = 345705650 and end_time > now() \G

*************************** 1. row ***************************

           id: 1

  select_type: SIMPLE

        table: xxxtable

         type: ref

possible_keys: idx_deller_id_end_time,idx_deller_id_start_time,idx_seller_item_start

          key: idx_deller_id_end_time

      key_len: 8 

          ref: const

         rows: 1726757

        Extra: Using where

1 row in set (0.00 sec) 

从key_len=8 和Extra: Using where 可以看出MySQL没有完全利用到idx_deller_id_end_time组合索引而是利用到了 selid字段作为过滤条件回表查询。
count(item_id)的意思是符合where条件的结果集中item_id非空集合的总和。
三 如何优化
根据该sql的业务需求是需要获取到某商家参加活动且活动截止时间大于当前时间的商品总数,可以使用如下sql满足要求:


select count(*) from xxxtable where selid = 345705650 and end_time > now() 

执行时间仅为原来的1/4,新的sql发布之后thread_running报警消失,业务校验时间明显缩短。


root@db >select count(*) from xxxtable where selid = 345705650 and end_time > now();
 
+----------+

| count(*) |

+----------+

| 2247052 |

+----------+

1 row in set (0.82 sec)

root@db >select count(1) from xxxtable where selid = 345705650 and end_time > now();

+----------+

| count(1) |

+----------+

| 2247052 |

+----------+

1 row in set (0.79 sec) 

优化后的sql的explain 方式如下:


root@db >explain select count(*) from xxxtable where selid = 345705650 and end_time > now() \G
 
*************************** 1. row ***************************

           id: 1

  select_type: SIMPLE

        table: xxxtable

         type: range

possible_keys: idx_deller_id_end_time,idx_deller_id_start_time,idx_seller_item_start

          key: idx_deller_id_end_time

      key_len: 16

          ref: NULL

         rows: 1726768

        Extra: Using where; Using index

1 row in set (0.00 sec) 

四 小结
 a 这个问题是在没有修改索引的基础中做出的优化,老的sql没有有效的利用当前的索引导致耗时操作
 b 对于不同count类型的sql 总结如下
   count(*)/count(1) 返回结果集的总和包括null和重复的值。
   count(column) 返回结果集中非空 column 的总和,执行查询的过程中会校验字段是否非空。
 c 在业务设计的时候 满足业务逻辑的前提下推荐使用count(*).
 d 从官方文档中摘录 Using where 和 Using index 的区别 


Using index
 
 The column information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row. This strategy can be used when the query uses only columns that are part of a single index.

 If the Extra column also says Using where, it means the index is being used to perform lookups of key values. Without Using where, the optimizer may be reading the index to avoid reading data rows but not using it for lookups. For example, if the index is a covering index for the query, the optimizer may scan it without using it for lookups. For InnoDB tables that have a user-defined clustered index, that index can be used even when Using index is absent from the Extra column. This is the case if type is index and key is PRIMARY.

 Using where

 A WHERE clause is used to restrict which rows to match against the next table or send to the client. Unless you specifically intend to fetch or examine all rows from the table, you may have something wrong in your query if the Extra value is not Using where and the table join type is ALL or index. Even if you are using an index for all parts of a WHERE clause, you may see Using where if the column can be NULL. 

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
13天前
|
分布式计算 关系型数据库 MySQL
大数据-88 Spark 集群 案例学习 Spark Scala 案例 SuperWordCount 计算结果数据写入MySQL
大数据-88 Spark 集群 案例学习 Spark Scala 案例 SuperWordCount 计算结果数据写入MySQL
38 3
|
13天前
|
SQL 关系型数据库 MySQL
案例剖析:MySQL唯一索引并发插入导致死锁!
案例剖析:MySQL唯一索引并发插入导致死锁!
案例剖析:MySQL唯一索引并发插入导致死锁!
|
13天前
|
SQL 关系型数据库 MySQL
案例剖析,MySQL共享锁引发的死锁问题!
案例剖析,MySQL共享锁引发的死锁问题!
|
13天前
|
消息中间件 关系型数据库 MySQL
大数据-117 - Flink DataStream Sink 案例:写出到MySQL、写出到Kafka
大数据-117 - Flink DataStream Sink 案例:写出到MySQL、写出到Kafka
63 0
|
1天前
|
存储 关系型数据库 MySQL
优化 MySQL 的锁机制以提高并发性能
【10月更文挑战第16天】优化 MySQL 锁机制需要综合考虑多个因素,根据具体的应用场景和需求进行针对性的调整。通过不断地优化和改进,可以提高数据库的并发性能,提升系统的整体效率。
4 1
|
1天前
|
缓存 关系型数据库 MySQL
一文彻底弄懂MySQL优化之深度分页
【10月更文挑战第24天】本文深入探讨了 MySQL 深度分页的原理、常见问题及优化策略。首先解释了深度分页的概念及其带来的性能和资源问题。接着介绍了基于偏移量(OFFSET)和限制(LIMIT)以及基于游标的分页方法,并分析了它们的优缺点。最后,提出了多种优化策略,包括合理创建索引、优化查询语句和使用数据缓存,帮助提升分页查询的性能和系统稳定性。
|
4天前
|
NoSQL 关系型数据库 MySQL
MySQL与Redis协同作战:百万数据量的优化实录
【10月更文挑战第6天】 在现代互联网应用中,随着用户量的增加和业务逻辑的复杂化,数据量级迅速增长,这对后端数据库系统提出了严峻的挑战。尤其是当数据量达到百万级别时,传统的数据库解决方案往往会遇到性能瓶颈。本文将分享一次使用MySQL与Redis协同优化大规模数据统计的实战经验。
20 3
|
4天前
|
NoSQL 关系型数据库 BI
记录一次MySQL+Redis实现优化百万数据统计的方式
【10月更文挑战第13天】 在处理百万级数据的统计时,传统的单体数据库往往力不从心,这时结合使用MySQL和Redis可以显著提升性能。以下是一次实际优化案例的详细记录。
18 1
|
11天前
|
SQL 关系型数据库 MySQL
在日常工作中怎么做MySQL优化的?
在日常工作中怎么做MySQL优化的?
|
2天前
|
监控 关系型数据库 MySQL
mysql8索引优化
综上所述,深入理解和有效实施这些索引优化策略,是解锁MySQL 8.0数据库高性能查询的关键。
9 0

热门文章

最新文章