1. 程式人生 > 資料庫 >MySQL去重該使用distinct還是group by?

MySQL去重該使用distinct還是group by?

前言

關於group by 與distinct 效能對比:網上結論如下,不走索引少量資料distinct效能更好,大資料量group by 效能好,走索引group by效能好。走索引時分組種類少distinct快。關於網上的結論做一次驗證。

準備階段遮蔽查詢快取

檢視MySQL中是否設定了查詢快取。為了不影響測試結果,需要關閉查詢快取。

show variables like '%query_cache%';

在這裡插入圖片描述

檢視是否開啟查詢快取決定於query_cache_typequery_cache_size

  • 方法一:關閉查詢快取需要找到my.ini,修改query_cache_type
    需要修改C:\ProgramData\MySQL\MySQL Server 5.7\my.ini配置檔案,修改query_cache_type=0或2
  • 方法二:設定query_cache_size為0,執行以下語句。
set global query_cache_size = 0;

方法三:如果你不想關閉查詢快取,也可以在使用RESET QUERY CACHE

現在測試環境中query_cache_type=2代表按需進行查詢快取,預設的查詢方式是不會進行快取,如需快取則需要在查詢語句中加上sql_cache

資料準備

t0表存放10W少量種類少的資料

drop table if exists t0;
create table t0(
id bigint primary key auto_increment,a varchar(255) not null
) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_bin;
1
2
3
4
5
drop procedure insert_t0_simple_category_data_sp;
delimiter //
create procedure insert_t0_simple_category_data_sp(IN num int)
begin
set @i = 0;
while @i < num do
	insert into t0(a) value(truncate(@i/1000,0));
 set @i = @i + 1;
end while;
end
//
call insert_t0_simple_category_data_sp(100000);

t1表存放1W少量種類多的資料

drop table if exists t1;
create table t1 like t0;
1
2
drop procedure insert_t1_complex_category_data_sp;
delimiter //
create procedure insert_t1_complex_category_data_sp(IN num int)
begin
set @i = 0;
while @i < num do
	insert into t1(a) value(truncate(@i/10,0));
 set @i = @i + 1;
end while;
end
//
call insert_t1_complex_category_data_sp(10000);

t2表存放500W大量種類多的資料

drop table if exists t2;
create table t2 like t1;
1
2
drop procedure insert_t2_complex_category_data_sp;
delimiter //
create procedure insert_t2_complex_category_data_sp(IN num int)
begin
set @i = 0;
while @i < num do
	insert into t1(a) value(truncate(@i/10,0));
 set @i = @i + 1;
end while;
end
//
call insert_t2_complex_category_data_sp(5000000);

測試階段

驗證少量種類少資料

未加索引

set profiling = 1;
select distinct a from t0;
show profiles;
select a from t0 group by a;
show profiles;
alter table t0 add index `a_t0_index`(a);

在這裡插入圖片描述

由此可見:少量種類少資料下,未加索引,distinct和group by效能相差無幾。

加索引

alter table t0 add index `a_t0_index`(a);

執行上述類似查詢後

在這裡插入圖片描述

由此可見:少量種類少資料下,加索引,distinct和group by效能相差無幾。

驗證少量種類多資料未加索引

執行上述類似未加索引查詢後

在這裡插入圖片描述

由此可見:少量種類多資料下,未加索引,distinct比group by效能略高,差距並不大。

加索引

alter table t1 add index `a_t1_index`(a);

執行類似未加索引查詢後

在這裡插入圖片描述

由此可見:少量種類多資料下,加索引,distinct和group by效能相差無幾。

驗證大量種類多資料

未加索引

SELECT count(1) FROM t2;

在這裡插入圖片描述

執行上述類似未加索引查詢後

在這裡插入圖片描述

由此可見:大量種類多資料下,未加索引,distinct比group by效能高。

加索引

alter table t2 add index `a_t2_index`(a);

執行上述類似加索引查詢後

在這裡插入圖片描述

由此可見:大量種類多資料下,加索引,distinct和group by效能相差無幾。

總結 效能比 少量種類少 少量種類多 大量種類多未加索引相差無幾distinct略優distinct更優加索引相差無幾相差無幾相差無幾

去重場景下,未加索引時,更偏向於使用distinct,而加索引時,distinct和group by兩者都可以使用。

總結

到此這篇關於MySQL去重該使用distinct還是group by?的文章就介紹到這了,更多相關mysql 去重distinct group by內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!