MySQL如何优化GROUP BY :松散索引扫描 VS 紧凑索引扫描
执行GROUP BY子句的最一般的方法:先扫描整个表,然后创建一个新的临时表,表中每个组的所有行应为连续的,最后使用该临时表来找到组
并应用聚集函数。在某些情况中,MySQL通过访问索引就可以得到结果,此类查询的 EXPLAIN 输出显示 Extra 列的值为 Using index for group-by。
一、松散索引扫描
The most efficient way to process GROUP BY is when an index is used to directly retrieve the grouping columns.
With this access method, MySQL uses the property of some index types that the keys are ordered (for example, BTREE).
This property enables use of lookup groups in an index without having to consider all keys in the index that satisfy all WHERE conditions.
This access method considers only a fraction of the keys in an index, so it is called a loose index scan.
When there is no WHERE clause, a loose index scan reads as many keys as the number of groups, which may be a much smaller number than that of all keys.
If the WHERE clause contains range predicates , a loose index scan looks up the first key of each group that satisfies the range conditions,
and again reads the least possible number of keys. This is possible under the following conditions:
The query is over a single table.
The
GROUP BYnames only columns that form a leftmost prefix of the index and no other columns.
(If, instead of GROUP BY, the query has a DISTINCT clause, all distinct attributes refer to columns that form a leftmost prefix of the index.)
For example, if a table t1 has an index on (c1,c2,c3),
loose index scan is applicable if the query has GROUP BY c1, c2,.
It is not applicable if the query has GROUP BY c2, c3 (the columns are not a leftmost prefix) or GROUP BY c1, c2, c4 (c4 is not in the index).
The only aggregate functions used in the select list (if any) are
MIN()andMAX(), and all of them refer to the same column. The column must be in the index and must immediately follow the columns in theGROUP BY.Any other parts of the index than those from the
GROUP BYreferenced in the query must be constants (that is, they must be referenced in equalities with constants), except for the argument ofMIN()orMAX()functions.For columns in the index, full column values must be indexed, not just a prefix. For example, with
c1 VARCHAR(20), INDEX (c1(10)), the index cannot be used for loose index scan.
mysql5.7示例如下:
CREATE TABLE `sm_wechat_binding` (
`id` bigint(20) NOT NULL,
`company_id` bigint(20) DEFAULT NULL,
`date_created` datetime NOT NULL,
`is_big_account` bit(1) NOT NULL,
`last_updated` datetime NOT NULL,
`open_id` varchar(64) NOT NULL,
`phone` varchar(14) DEFAULT NULL,
`deleted` datetime DEFAULT NULL,
`imported` datetime DEFAULT NULL,
`client_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `company_id_idx` (`company_id`),
KEY `openid_phone_index` (`open_id`,`phone`),
CONSTRAINT `FK_f95swnll9d3myf1pl7o5cxtws` FOREIGN KEY (`company_id`) REFERENCES `sm_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
mysql> EXPLAIN SELECT distinct company_id FROM sm_wechat_binding;
+----+-------------+-------------------+-------+----------------+----------------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------------+-------+----------------+----------------+---------+------+------+--------------------------+
| 1 | SIMPLE | sm_wechat_binding | range | company_id_idx | company_id_idx | 9 | NULL | 699 | Using index for group-by |
+----+-------------+-------------------+-------+----------------+----------------+---------+------+------+--------------------------+
1 row in set (0.02 sec) mysql> EXPLAIN SELECT COUNT( company_id) FROM sm_wechat_binding GROUP BY company_id;
+----+-------------+-------------------+-------+----------------+----------------+---------+------+-------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------------+-------+----------------+----------------+---------+------+-------+-------------+
| 1 | SIMPLE | sm_wechat_binding | index | company_id_idx | company_id_idx | 9 | NULL | 39130 | Using index |
+----+-------------+-------------------+-------+----------------+----------------+---------+------+-------+-------------+
1 row in set (0.00 sec) mysql> EXPLAIN SELECT COUNT(distinct company_id) FROM sm_wechat_binding GROUP BY company_id;
+----+-------------+-------------------+-------+----------------+----------------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------------+-------+----------------+----------------+---------+------+------+--------------------------+
| 1 | SIMPLE | sm_wechat_binding | range | company_id_idx | company_id_idx | 9 | NULL | 699 | Using index for group-by |
+----+-------------+-------------------+-------+----------------+----------------+---------+------+------+--------------------------+
1 row in set (0.00 sec) mysql> EXPLAIN SELECT COUNT(distinct company_id) as num, company_id FROM sm_wechat_binding GROUP BY company_id;
+----+-------------+-------------------+-------+----------------+----------------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------------+-------+----------------+----------------+---------+------+------+--------------------------+
| 1 | SIMPLE | sm_wechat_binding | range | company_id_idx | company_id_idx | 9 | NULL | 699 | Using index for group-by |
+----+-------------+-------------------+-------+----------------+----------------+---------+------+------+--------------------------+
1 row in set (0.00 sec) mysql> EXPLAIN SELECT max(company_id), min(company_id) FROM sm_wechat_binding force index(company_id_idx);
+----+-------------+-------+------+---------------+------+---------+------+------+------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+------------------------------+
| 1 | SIMPLE | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Select tables optimized away |
+----+-------------+-------+------+---------------+------+---------+------+------+------------------------------+
1 row in set (0.01 sec)
示例二
mysql> CREATE TABLE `loose_index_scan` (
->
-> `c1` int(11) DEFAULT NULL,
-> `c2` int(11) DEFAULT NULL,
-> `c3` int(11) DEFAULT NULL,
-> `c4` int(11) DEFAULT NULL,
-> KEY `idx_g` (`c1`,`c2`,`c3`)
-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.90 sec) mysql>
mysql>
mysql> explain select c1,c2 from loose_index_scan group by c1,c2;
+----+-------------+------------------+-------+---------------+-------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------------+-------+---------------+-------+---------+------+------+-------------+
| 1 | SIMPLE | loose_index_scan | index | idx_g | idx_g | 15 | NULL | 1 | Using index |
+----+-------------+------------------+-------+---------------+-------+---------+------+------+-------------+
1 row in set (0.06 sec) mysql>
mysql>
mysql> EXPLAIN SELECT COUNT(DISTINCT c1) FROM loose_index_scan GROUP BY c1;
+----+-------------+------------------+-------+---------------+-------+---------+------+------+-------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------------+-------+---------------+-------+---------+------+------+-------------------------------------+
| 1 | SIMPLE | loose_index_scan | range | idx_g | idx_g | 5 | NULL | 2 | Using index for group-by (scanning) |
+----+-------------+------------------+-------+---------------+-------+---------+------+------+-------------------------------------+
1 row in set (0.02 sec)
参考:
MySQL如何优化GROUP BY :松散索引扫描 VS 紧凑索引扫描的更多相关文章
- MySQL优化GROUP BY-松散索引扫描与紧凑索引扫描
满足GROUP BY子句的最一般的方法是扫描整个表并创建一个新的临时表,表中每个组的所有行应为连续的,然后使用该临时表来找到组并应用累积函数(如果有).在某些情况中,MySQL能够做得更好,即通过索引 ...
- MySQL松散索引扫描与紧凑索引扫描
什么是松散索引? 答:实际上就是当MySQL 完全利用索引扫描来实现GROUP BY 的时候,并不需要扫描所有满足条件的索引键即可完成操作得出结果. 要利用到松散索引扫描实现GROUP BY,需要至少 ...
- mysql数据库优化之 如何选择合适的列建立索引
1. 在where 从句,group by 从句,order by 从句,on 从句中出现的列: 2. 索引字段越小越好: 3. 离散度大的列放到联合索引的前面:比如: select * from p ...
- MySQL架构优化实战系列1:数据类型与索引调优全解析
一.数据类型优化 数据类型 整数 数字类型:整数和实数 tinyint(8).smallint(16).mediuint(24).int(32).bigint(64) 数字表示对应最大存储位数,如 ...
- MySql数据库 优化
MySQL数据库优化方案 Mysql的优化,大体可以分为三部分:索引的优化,sql慢查询的优化,表的优化. 开启慢查询日志,可以让MySQL记录下查询超过指定时间的语句,通过定位分析性能的瓶颈,才能更 ...
- mysql 松散索引与紧凑索引扫描(引入数据结构)
这一篇文章本来应该是放在 mysql 高性能日记中的,并且其优化程度并不高,但考虑到其特殊性和原理(索引结构也在这里稍微讲一下) 一,mysql 索引结构 (B.B+树) 要问到 mysql 的索引用 ...
- mysql 通过使用联全索引优化Group by查询
/*SELECT count(*) FROM (*/ EXPLAIN SELECT st.id,st.Stu_name,tmpgt.time,tmpgt.goutong FROM jingjie_st ...
- MySQL性能优化——索引
原文地址:http://blog.codinglabs.org/articles/theory-of-mysql-index.html InnoDB使用B+Tree作为索引结构 最左前缀原理与相关优化 ...
- mysql性能优化-慢查询分析、优化索引和配置
一.优化概述 二.查询与索引优化分析 1性能瓶颈定位 Show命令 慢查询日志 explain分析查询 profiling分析查询 2索引及查询优化 三.配置优化 1) max_connec ...
随机推荐
- Spring核心项目及微服务架构方向
spring 顶级项目:Spring IO platform:用于系统部署,是可集成的,构建现代化应用的版本平台,具体来说当你使用maven dependency引入spring jar包时它就在工作 ...
- Atitit. atiOrder Order 订单管理框架的设计
Atitit. atiOrder Order 订单管理框架的设计 1. Order 订单处理流程1 2. code2 3. Ref7 1. Order 订单处理流程 if(userSvr.isNo ...
- IDEA13中配置struts错误:ClassNotFoundException: org...dispatcher.ng.filter.StrutsPrepareAndExecuteFilter +找不到java程序包 解决办法
问题一:ClassNotFoundException: org...dispatcher.ng.filter.StrutsPrepareAndExecuteFilter解决办法 1.确保所有strut ...
- libevent源码学习_event结构体
在libevent中最重要的结构体莫过于event和event_base了,下面对于这2个结构体进行分析. 1.结构体event,位于:event.h struct event { /* * 双向链表 ...
- Web前端都学点儿啥?
Web开发如今是如日中天,热的发烫.但是Web开发相关的技术和知识却像N座大山一样,耸立在我们面前,连绵起伏,漫无边际.那么这些山头那些我们应该占领,那些我们应该绕开,很多人看着就蒙了,这不光是初学者 ...
- mySQL 开启事件存储过程
怎样在Navicat中设置,是数据库按照记录中的日期更新状态字段 其实这个很常用,比如你网站里的某条记录的日期——比如说数据库中某条活动记录的审核日期字段已经过期,亦即当前时间已经超过审核日期,那么定 ...
- shiro session过期后ajax请求跳转(转)
配置了 Shrio框架,session也集成进去了 ,发现问题session会话过期,点击页面,一直请求失败.本来想集成拦截器,过滤器,但是已经用了shiro框架,sessionDestroyed 方 ...
- 在linux下使用curl
使用curl从 ftp下载文件 curl ftp://192.168.31.164/lrzsz-0.12.20.tar.gz --user root:123456 -o lrzsz-0.12.20.t ...
- 接入qq登录功能出现的问题
在调用qq授权的接口时,出现以上错误. 原因是: 打包的应用签名和第一次上传包的签名不一致造成的 解决方法: 第一种方法:用上次打包apk的keystore重新打包apk,使签名一致. 第二种方法:联 ...
- js保留几位小数
function reservedDecimal(val, digit) { return Number(val).toFixed(digit);} 调用 reservedDecimal(10,2); ...