最近在网上看到了一些测试,感觉不是很准确,今天亲自测试了一番。得出了结论,测试过程在个人计算机上,可能不够全面,仅供参考。
测试过程:
准备一张测试表
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有了更深入的了解,希望对大家的学习有所帮助。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“MySQL中distinct与group by之间的性能进行比较”评论...
更新日志
2024年07月05日
2024年07月05日
- 任贤齐.2010-任贤齐创作集音乐旅行者【滚石】【WAV+CUE】
- dnf攻击属性怎么点亮
- 魔兽世界有哪些GM命令 魔兽世界GM命令大全介绍
- dnf攻速鞋怎么才算140
- 群星2012-Sampler发烧中的精选(国语)4辑[新世纪][WAV+CUE]
- [发烧人声]群星《发烧中的精选SAMPLERAUDIOPHILE》AMCD限量版[WAV+CUE]
- 中唱唱片群星《好歌珍藏-激情年代》2CD【WAV】
- 王韵婵.1996-需要【现代派】【WAV+CUE】
- 群星.2024-你就在我身边电影原声专辑【奔跑怪物】【FLAC分轨】
- 何映达.1990-孤独地拥有你【蓝与白】【WAV+CUE】
- dnf新鲜冒险奇闻有什么用
- dnf无色套是哪几件
- dnf旭旭宝宝红眼装备是什么搭配
- 陈思安2005-我无醉[华特][WAV+CUE]
- 张美玲2013-我知道你也爱我[南方][WAV+CUE]