这篇文章主要针对MySQL中distinct与group by之间的性能进行比较,内容比较详细,很直观的能看出比较结果,感兴趣的小伙伴们可以参考一下 最近在网上看到了一些测试,感觉不是很准确,

这篇文章主要针对MySQL中distinctgroup by之间的性能进行比较,内容比较详细,很直观的能看出比较结果,感兴趣的小伙伴们可以参考一下    

最近在网上看到了一些测试,感觉不是很准确,今天亲自测试了一番。得出了结论,测试过程在个人计算机上,可能不够全面,仅供参考。

测试过程:
准备一张测试表 
 

  1. CREATE TABLE `test_test` ( 
  2.   `id` int(11) NOT NULL auto_increment, 
  3.   `num` int(11) NOT NULL default '0', 
  4.   PRIMARY KEY (`id`) 
  5.   ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; 
?

建个储存过程向表中插入10W条数据    
 

  1. create procedure p_test(pa int(11))  
  2.  begin 
  3.   
  4.  declare max_num int(11) default 100000;  
  5.  declare i int default 0;  
  6.  declare rand_num int;  
  7.   
  8.  select count(id) into max_num from test_test;  
  9.   
  10.  while i < pa do  
  11.    if max_num < 100000 then 
  12.      select cast(rand()*100 as unsigned) into rand_num;  
  13.      insert into test_test(num)values(rand_num);  
  14.    end if;  
  15.    set i = i +1;  
  16.  end while;  
  17.  end 
?

调用存储过程插入数据
 

  1. call p_test(100000); 
?

开始测试:(不加索引)
 

  1. select distinct num from test_test;  
  2. select num from test_test group by num;  
  3.   
  4. [SQL] select distinct num from test_test; 
  5. 受影响的行: 0 
  6. 时间: 0.078ms 
  7.   
  8. [SQL]  
  9. select num from test_test group by num; 
  10. 受影响的行: 0 
  11. 时间: 0.031ms 
?

 

二、num字段上创建索引
 

  1. ALTER TABLE `test_test` ADD INDEX `num_index` (`num`) ; 
?

再次查询   
 

  1. select distinct num from test_test;  
  2. select num from test_test group by num;  
  3. [SQL] select distinct num from test_test; 
  4. 受影响的行: 0 
  5. 时间: 0.000ms 
  6.   
  7. [SQL]  
  8. select num from test_test group by num; 
  9. 受影响的行: 0 
  10. 时间: 0.000ms 
?

MySQL中distinct与group by之间的性能进行比较(mysql distinct和group by区别)  MySQL distinct group by 第1张

这时候我们发现时间太小了 0.000秒都无法精确了。
我们转到命令行下测试
 

  1. MySQL> set profiling=1; 
  2. mysql> select distinct(num) from test_test;  
  3. mysql> select num from test_test group by num; 
  4. mysql> show profiles; 
  5. +----------+------------+----------------------------------------+ 
  6. | Query_ID | Duration | Query         | 
  7. +----------+------------+----------------------------------------+ 
  8. |  1 | 0.00072550 | select distinct(num) from test_test | 
  9. |  2 | 0.00071650 | select num from test_test group by num | 
  10. +----------+------------+----------------------------------------+ 
?

分析:
加了索引之后 distinct 比没加索引的distinct 快了107倍。
加了索引之后 group by 比没加索引的group by 快了43倍。
再来对比 :distinct 和group by
不管是加不加索引group by 都比distinct 快。

因此使用的时候建议选 group by。

以上就是在MySQL中distinct与group by之间的性能进行比较的,通过以上比较是不是对distinct和group by有了更深入的了解,希望对大家的学习有所帮助。



注:相关教程知识阅读请移步到MYSQL教程频道。
转载请说明出处
知优网 » MySQL中distinct与group by之间的性能进行比较(mysql distinct和group by区别)

发表评论

您需要后才能发表评论