mysql group by和dis_mysql下distinct和group by区别对比
在數據表中記錄了用戶驗證時使用的書目,現在想取出所有書目,用DISTINCT和group by都取到了我想要的結果,但我發現返回結果排列不同,distinct會按數據存放順序一條條顯示,而group by會做個排序(一般是ASC)。
DISTINCT 實際上和 GROUP BY 操作的實現非常相似,只不過是在 GROUP BY 之后的每組中只取出一條記錄而已。所以,DISTINCT 的實現和 GROUP BY 的實現也基本差不多,沒有太大的區別,同樣可以通過松散索引掃描或者是緊湊索引掃描來實現。
那DISTINCT 和GROUP BY哪個效率更高?
DISTINCT操作只需要找出所有不同的值就可以了。而GROUP BY操作還要為其他聚集函數進行準備工作。從這一點上將,GROUP BY操作做的工作應該比DISTINCT所做的工作要多一些。
但實際上,GROUP BY 效率會更高點,為什么呢?對于DISTINCT操作,它會讀取了所有記錄,而GROUP BY需要讀取的記錄數量與分組的組數量一樣多,也就是說比實際存在的記錄數目要少很多。
例子? aa表?????? a????????? b
123??????? 10
123??????? 12
1234?????? 11
1234???????? 14
首先 group 是用來分組的? 不是過濾重復項的。重復項刪除語句 DISTINCT用這個 。?select? DISTINCT(a) from aa
結果就是???? a
123
1234
group by用來分組的
select a, sum(b) from aa group by a
sum意思是總和。結果就是
a???????? b
123????? 22
1234??? 25
語句的目的是以a為目標 需要知道 相同名字的物品?? 在b列一共有多少數量總和
select a,count(b)? from aa group by a
count 意思行數總和?? 結果就是
a???????? b
123????? 2
1234??? 2
語句目的是? 相同名字的物品 一共有幾行
MySQL中distinct和group by性能比較
測試過程:
準備一張測試表
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
調用存儲過程插入數據
1?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
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
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 group by和dis_mysql下distinct和group by区别对比的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网站图标 favicon.ico 快速在
- 下一篇: 三:Planning and Manag