select rand()100 int mysql_MySQL中distinct与groupby之间的性能进行比较

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

测试过程:

准备一张测试表

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

20824748b542edf55fc57e9b033746cb.png

二、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

62ac030a5ad75f09a28bb9359c2fb404.png

这时候我们发现时间太小了 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 |

+----------+------------+----------------------------------------+

29ff4f08637650d2a0b933546510b4b9.png

分析:

加了索引之后distinct 比没加索引的distinct 快了107倍。加了索引之后group by 比没加索引的group by 快了43倍。再来对比 :distinct 和group by

不管是加不加索引group by 都比distinct 快。

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

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

您可能感兴趣的文章:MySQL中distinct与group by语句的一些比较及用法讲解

MySQL中distinct语句的基本原理及其与group by的比较

MySQL中索引优化distinct语句及distinct的多字段操作

MySQL中distinct语句去查询重复记录及相关的性能讨论

MySQL中Distinct和Group By语句的基本使用教程

MySQL中distinct和count(*)的使用方法比较

分析MySQL中优化distinct的技巧

解析mysql中:单表distinct、多表group by查询去除重复记录

使用distinct在mysql中查询多条不重复记录值的解决办法

MySQL关键字Distinct的详细介绍

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值