AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > MySQL

MySQL中distinct与group by之间的性能进行比较

51自学网 http://www.wanshiok.com

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

?
1
2
3
4
5
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条数据    

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

调用存储过程插入数据

?
1
call p_test(100000);

开始测试:(不加索引)

?
1
2
3
4
5
6
7
8
9
10
11
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字段上创建索引

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

再次查询   

?
1
2
3
4
5
6
7
8
9
10
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秒都无法精确了。
我们转到命令行下测试

?
1
2
3
4
5
6
7
8
9
10
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 |
+----------+------------+----------------------------------------+


 
上一篇:MySQL查询优化的5个实用技巧  下一篇:关于MySQL 优化的100个的建议