前言

关于group by 与distinct 性能对比:网上结论如下,不走索引少量数据distinct性能更好,大数据量group by 性能好,走索引group by性能好。走索引时分组种类少distinct快。关于网上的结论做一次验证。

准备阶段屏蔽查询缓存

查看MySQL中是否设置了查询缓存。为了不影响测试结果,需要关闭查询缓存。

show variables like '%query_cache%';

现在测试环境中query_cache_type=2代表按需进行查询缓存,默认的查询方式是不会进行缓存,如需缓存则需要在查询语句中加上sql_cache

数据准备

t0表存放10W少量种类少的数据

drop table if exists t0;create table t0(id bigint primary key auto_increment,a varchar(255) not null) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_bin;12345drop procedure insert_t0_simple_category_data_sp;delimiter //create procedure insert_t0_simple_category_data_sp(IN num int)beginset @i = 0;while @i < num doinsert into t0(a) value(truncate(@i/1000, 0)); set @i = @i + 1;end while;end//call insert_t0_simple_category_data_sp(100000);
drop table if exists t1;create table t1 like t0;12drop procedure insert_t1_complex_category_data_sp;delimiter //create procedure insert_t1_complex_category_data_sp(IN num int)beginset @i = 0;while @i < num doinsert into t1(a) value(truncate(@i/10, 0)); set @i = @i + 1;end while;end//call insert_t1_complex_category_data_sp(10000);
drop table if exists t2;create table t2 like t1;12drop procedure insert_t2_complex_category_data_sp;delimiter //create procedure insert_t2_complex_category_data_sp(IN num int)beginset @i = 0;while @i < num doinsert into t1(a) value(truncate(@i/10, 0)); set @i = @i + 1;end while;end//call insert_t2_complex_category_data_sp(5000000);

验证少量种类少数据

未加索引

set profiling = 1;select distinct a from t0;show profiles;select a from t0 group by a;show profiles;alter table t0 add index `a_t0_index`(a);

加索引

alter table t0 add index `a_t0_index`(a);

在这里插入图片描述

由此可见:少量种类少数据下,加索引,distinct和group by性能相差无几。

验证少量种类多数据未加索引

执行上述类似未加索引查询后

在这里插入图片描述

由此可见:少量种类多数据下,未加索引,distinct比group by性能略高,差距并不大。

加索引

alter table t1 add index `a_t1_index`(a);

在这里插入图片描述

由此可见:少量种类多数据下,加索引,distinct和group by性能相差无几。

验证大量种类多数据

未加索引

SELECT count(1) FROM t2;

在这里插入图片描述

由此可见:大量种类多数据下,未加索引,distinct比group by性能高。

加索引

alter table t2 add index `a_t2_index`(a);

在这里插入图片描述

由此可见:大量种类多数据下,加索引,distinct和group by性能相差无几。

总结性能比少量种类少少量种类多大量种类多未加索引相差无几distinct略优distinct更优加索引相差无几相差无几相差无几

去重场景下,未加索引时,更偏向于使用distinct,而加索引时,distinct和group by两者都可以使用。

总结

更多相关文章

  1. MySQL系列多表连接查询92及99语法示例详解教程
  2. Linux下MYSQL 5.7 找回root密码的问题(亲测可用)
  3. MySQL 什么时候使用INNER JOIN 或 LEFT JOIN
  4. android从服务器下载文件(php+apache+win7+MySql)
  5. 【有图】android通过jdbc连接mysql(附文件)
  6. android 通过php 连接 mysql
  7. android通过php连接mysql数据库!!!!
  8. 关于Android连接远程数据库(mysql、oracle)
  9. 图书馆座位管理系统(android,java后台,mysql)

随机推荐

  1. 深度解析C++的函数模板与类模板
  2. 如何快速生成数据的文本路径呢?C++实现文
  3. 如何使用LINQ、Lambda 表达式 、委托快速
  4. C#中将DataGridView中的数据导入到Csv文
  5. C#学习记录:编写高质量代码改善整理建议9-
  6. c# 如何生成自定义图片?c# 生成自定义图片
  7. C#学习记录:编写高质量代码改善整理建议4-
  8. c++中string&char *&char[]之间如何转换(
  9. 基于C的文件操作 (FILE*、fstream、window
  10. C#学习记录:编写高质量代码改善整理建议1-