MySQL中distinct與group by之間的效能進行比較_Mysql

來源:互聯網
上載者:User

最近在網上看到了一些測試,感覺不是很準確,今天親自測試了一番。得出了結論,測試過程在個人電腦上,可能不夠全面,僅供參考。

測試過程:
準備一張測試表 

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有了更深入的瞭解,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.