CREATE TABLE `staff` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`name` varchar(64) NOT NULL COMMENT '姓名',
`age` int(4) NOT NULL COMMENT '年龄',
`city` varchar(64) NOT NULL COMMENT '城市',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COMMENT='员工表';
explain select city ,count(*) as num from staff group by city;
group by optimization
order by null does not sort
explain select city ,count(*) as num from staff group by city order by null
There is only Using temporary, there is no Using filesort, indicating that the sorting is not performed.
Group field plus index
alter table staff add index idx_city(city)
explain select city ,count(*) as num from staff group by city
Using index, indicating that the index is covered, the type is inde, indicating that the index idx_city has been traversed
Using temporary and Using filesort are all gone
DROP INDEX idx_city ON staff
Use in-memory temporary tables as much as possible
Use SQL_BIG_RESULT
explain select SQL_BIG_RESULT city ,count(*) as num from staff group by city
Reference blog
[1]https://mp.weixin.qq.com/s/EybebcYX4i13r5nDRG14fg
[2]https://juejin.cn/post/7053966777088213005