【案例】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 whe...
一 背景
 某业务的数据库定期报 thread_runing 飙高,通定位发现一个慢查询sql导致会话堆积。执行sql 耗时如下 

  1. root@db 05:32:05>select count(item_id) from xxxtable where selid = 345705650 and end_time > now();
  2. +----------------+
  3. | count(item_id) |
  4. +----------------+
  5. | 2247052 |
  6. +----------------+
  7. 1 row in set (4.65 sec)
二 分析   
慢查询表结构如下 
  1. root@db >show create table xxxtable \G
  2. *************************** 1. row ***************************
  3.        Table: uac_shop_item_promotion_0091
  4. Create Table: CREATE TABLE `uac_shop_item_promotion_0091` (
  5.   `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  6.   `gmt_modified` datetime NOT NULL COMMENT '修改时间',
  7.   `selid` bigint(20) NOT NULL COMMENT '分表字段',
  8.   `end_time` datetime NOT NULL COMMENT '活动结束时间',
  9.   `item_id` bigint(20) NOT NULL COMMENT '商品id',
  10.   PRIMARY KEY (`id`),
  11.   UNIQUE KEY `idx_uq_item` (`item_id`),
  12.   KEY `idx_deller_id_end_time` (`selid`,`end_time`),
  13.   KEY `idx_deller_id_start_time` (`selid`,`start_time`),
  14.   KEY `idx_seller_item_start` (`selid`,`start_time`,`item_id`)
  15. ) ENGINE=InnoDB AUTO_INCREMENT=42132149 DEFAULT CHARSET=gbk COMMENT='索引表'
  16. 1 row in set (0.00 sec)
很明显出现问题的sql由于使用了count(item_id) ,而item_id字段并没有和 selid 和end_time 构成有效索引  故该sql 没有合理的使用索引 。查看其直系计划
  1. root@db >explain select count(item_id) from xxxtable
  2.         >where selid = 345705650 and end_time > now() \G
  3. *************************** 1. row ***************************
  4.            id: 1
  5.   select_type: SIMPLE
  6.         table: xxxtable
  7.          type: ref
  8. possible_keys: idx_deller_id_end_time,idx_deller_id_start_time,idx_seller_item_start
  9.           key: idx_deller_id_end_time
  10.       key_len: 8
  11.           ref: const
  12.          rows: 1726757
  13.         Extra: Using where
  14. 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满足要求:
  1. select count(*) from xxxtable where selid = 345705650 and end_time > now()
执行时间仅为原来的1/4,新的sql发布之后thread_running报警消失,业务校验时间明显缩短。
  1. root@db >select count(*) from xxxtable where selid = 345705650 and end_time > now();
  2. +----------+
  3. | count(*) |
  4. +----------+
  5. | 2247052 |
  6. +----------+
  7. 1 row in set (0.82 sec)
  8. root@db >select count(1) from xxxtable where selid = 345705650 and end_time > now();
  9. +----------+
  10. | count(1) |
  11. +----------+
  12. | 2247052 |
  13. +----------+
  14. 1 row in set (0.79 sec)
优化后的sql的explain 方式如下:
  1. root@db >explain select count(*) from xxxtable where selid = 345705650 and end_time > now() \G
  2. *************************** 1. row ***************************
  3.            id: 1
  4.   select_type: SIMPLE
  5.         table: xxxtable
  6.          type: range
  7. possible_keys: idx_deller_id_end_time,idx_deller_id_start_time,idx_seller_item_start
  8.           key: idx_deller_id_end_time
  9.       key_len: 16
  10.           ref: NULL
  11.          rows: 1726768
  12.         Extra: Using where; Using index
  13. 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 的区别 
  1. Using index
  2.  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.
  3.  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.
  4.  Using where
  5.  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
目录
相关文章
|
11月前
|
NoSQL 关系型数据库 MySQL
MySQL学习笔记-不同count统计的比较
MySQL学习笔记-不同count统计的比较
63 0
|
SQL 存储 关系型数据库
为什么mysql的count()方法这么慢?
为什么mysql的count()方法这么慢?
88 0
|
关系型数据库 MySQL 大数据
【大数据系列之MySQL】(十一):MySQL中select语句查询用法
【大数据系列之MySQL】(十一):MySQL中select语句查询用法
269 0
【大数据系列之MySQL】(十一):MySQL中select语句查询用法
|
存储 SQL 缓存
MySQL执行查询的内部原理
MySQL执行查询的内部原理
96 0
MySQL执行查询的内部原理
|
关系型数据库 MySQL 测试技术
软件测试mysql面试题:mysql 随机查询表“test”的 10 条数据?
软件测试mysql面试题:mysql 随机查询表“test”的 10 条数据?
99 0
|
存储 缓存 关系型数据库
MySQL COUNT 函数及其优化
MySQL COUNT 优化 MyISAM InnoDB
296 0
MySQL COUNT 函数及其优化
|
SQL 关系型数据库 MySQL
《零基础》MySQL 查询数据(十二)
MySQL 数据库使用SQL SELECT语句来查询数据。 你可以通过 m
107 0
《零基础》MySQL 查询数据(十二)
|
SQL NoSQL 关系型数据库
MySQL 更新操作案例分析
本文将通过一个 用户账户金额更新的案例 分析几种数据更新的操作的优劣。希望对大家有帮助 🐶。 数据库版本 : mysql 5.7.23
136 0
|
SQL 关系型数据库 MySQL