MySQL中distinct和group by性能比較


MySQL中distinct和group 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條數據 

01    create procedure p_test(pa int(11)) 
02     begin 
03       
04      declare max_num int(11) default 100000; 
05      declare i int default 0; 
06      declare rand_num int; 
07       
08      select count(id) into max_num from test_test; 
09       
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);

開始測試:(不加索引)

01    select distinct num from test_test; 
02    select num from test_test group by num; 
03     
04    [SQL] select distinct num from test_test;
05    受影響的行: 0
06    時間: 0.078ms
07     
08    [SQL]  
09    select num from test_test group by num;
10    受影響的行: 0
11    時間: 0.031ms

二、num字段上創建索引

 

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

 

再次查詢

01    select distinct num from test_test; 
02    select num from test_test group by num; 
03    [SQL] select distinct num from test_test;
04    受影響的行: 0
05    時間: 0.000ms
06     
07    [SQL]  
08    select num from test_test group by num;
09    受影響的行: 0
10    時間: 0.000ms

這時候我們發現時間太小了 0.000秒都無法精確了。

 

我們轉到命令行下 測試

01    mysql> set profiling=1;
02    mysql> select distinct(num) from test_test; 
03    mysql> select num from test_test group by num;
04    mysql> show profiles;
05    +----------+------------+----------------------------------------+
06    | Query_ID | Duration   | Query                                  |
07    +----------+------------+----------------------------------------+
08    |        1 | 0.00072550 | select distinct(num) from test_test    |
09    |        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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM