MySQL中distinct与group by之间的性能进行比较
网络编程 2021-07-05 15:28www.168986.cn编程入门
这篇文章主要针对MySQL中distinct与group by之间的性能进行比较,内容比较详细,很直观的能看出比较结果,感兴趣的小伙伴们可以参考一下
最近在网上看到了一些测试,感觉不是很准确,今天亲自测试了一番。得出了结论,测试过程在个人计算机上,可能不够全面,仅供参考。
测试过程
准备一张测试表
CREATE TABLE `test_test` ( `id` int(11) NOT NULL auto_increment, `num` int(11) NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
建个储存过程向表中插入10W条数据
create procedure p_test(pa int(11)) begin declare max_num int(11) default 100000; declare i int default 0; declare rand_num int; select count(id) into max_num from test_test; while i < pa do if max_num < 100000 then select cast(rand()100 as unsigned) into rand_num; insert into test_test(num)values(rand_num); end if; set i = i +1; end while; end
调用存储过程插入数据
call p_test(100000);
开始测试(不加索引)
select distinct num from test_test; select num from test_test group by num; [SQL] select distinct num from test_test; 受影响的行: 0 时间: 0.078ms [SQL] select num from test_test group by num; 受影响的行: 0 时间: 0.031ms
二、num字段上创建索引
ALTER TABLE `test_test` ADD INDEX `num_index` (`num`) ;
查询
select distinct num from test_test; select num from test_test group by num; [SQL] select distinct num from test_test; 受影响的行: 0 时间: 0.000ms [SQL] select num from test_test group by num; 受影响的行: 0 时间: 0.000ms
这时候我们发现时间太小了 0.000秒都无法精确了。
我们转到命令行下测试
mysql> set profiling=1; mysql> select distinct(num) from test_test; mysql> select num from test_test group by num; mysql> show profiles; +----------+------------+----------------------------------------+ | Query_ID | Duration | Query | +----------+------------+----------------------------------------+ | 1 | 0.00072550 | select distinct(num) from test_test | | 2 | 0.00071650 | select num from test_test group by num | +----------+------------+----------------------------------------+
分析
加了索引之后 distinct 比没加索引的distinct 快了107倍。
加了索引之后 group by 比没加索引的group by 快了43倍。
再来对比 distinct 和group by
不管是加不加索引group by 都比distinct 快。
使用的时候建议选 group by。
以上就是在MySQL中distinct与group by之间的性能进行比较的,通过以上比较是不是对distinct和group by有了更深入的了解,希望对大家的学习有所帮助。
编程语言
- 甘肃哪有关键词排名优化购买方式有哪些
- 甘肃SEO如何做网站优化
- 河南seo关键词优化怎么做电话营销
- 北京SEO优化如何做QQ群营销
- 来宾百度关键词排名:提升您网站曝光率的关键
- 卢龙关键词优化:提升您网站排名的策略与技巧
- 山东网站优化的注意事项有哪些
- 四川整站优化怎样提升在搜索引擎中的排名
- 疏附整站优化:提升网站性能与用户体验的全新
- 海南seo主要做什么工作售后服务要做到哪些
- 荣昌百度网站优化:提升您网站的搜索引擎排名
- 河北seo网站排名关键词优化如何做SEO
- 江西优化关键词排名推广售后保障一般有哪些
- 古浪SEO优化:提升你的网站可见性
- 西藏网站排名优化怎么把网站排名在百度首页
- 如何提升阳东百度快照排名:详尽指南