面試突擊:MySQL 中如何去重?
作者 | 磊哥
來源 | Java面試真題解析(ID:aimianshi666)
轉(zhuǎn)載請聯(lián)系授權(quán)(微信ID:GG_Stone)
在 MySQL 中,最常見的去重方法有兩個(gè):使用 distinct 或使用 group by,那它們有什么區(qū)別呢?接下來我們一起來看。
1、創(chuàng)建測試數(shù)據(jù)
-- 創(chuàng)建測試表
drop table if exists pageview;
create table pageview(
id bigint primary key auto_increment comment '自增主鍵',
aid bigint not null comment '文章ID',
uid bigint not null comment '(訪問)用戶ID',
createtime datetime default now() comment '創(chuàng)建時(shí)間'
) default charset='utf8mb4';
-- 添加測試數(shù)據(jù)
insert into pageview(aid,uid) values(1,1);
insert into pageview(aid,uid) values(1,1);
insert into pageview(aid,uid) values(2,1);
insert into pageview(aid,uid) values(2,2);
最終展現(xiàn)效果如下:
2、distinct 使用
distinct 基本語法如下:
SELECT DISTINCT column_name,column_name FROM table_name;
(1)單列去重
我們先用 distinct 實(shí)現(xiàn)單列去重,根據(jù) aid(文章 ID)去重,具體實(shí)現(xiàn)如下:
(2)多列去重
除了單列去重之外,distinct 還支持多列(兩列及以上)去重,我們根據(jù) aid(文章 ID)和 uid(用戶 ID)聯(lián)合去重,具體實(shí)現(xiàn)如下:
(3)聚合函數(shù)+去重
使用 distinct + 聚合函數(shù)去重,計(jì)算 aid 去重之后的總條數(shù),具體實(shí)現(xiàn)如下:
3、group by 使用
group by 基礎(chǔ)語法如下:
SELECT column_name,column_name FROM table_name
WHERE column_name operator value
GROUP BY column_name
(1)單列去重
根據(jù) aid(文章 ID)去重,具體實(shí)現(xiàn)如下:
與 distinct 相比 group by 可以顯示更多的列,而 distinct 只能展示去重的列。
(2)多列去重
根據(jù) aid(文章 ID)和 uid(用戶 ID)聯(lián)合去重,具體實(shí)現(xiàn)如下:
(3)聚合函數(shù) + group by
統(tǒng)計(jì)每個(gè) aid 的總數(shù)量,SQL 實(shí)現(xiàn)如下:從上述結(jié)果可以看出,使用 group by 和 distinct 加 count 的查詢語義是完全不同的,distinct + count 統(tǒng)計(jì)的是去重之后的總數(shù)量,而 group by + count 統(tǒng)計(jì)的是分組之后的每組數(shù)據(jù)的總數(shù)。
4、distinct 和 group by 的區(qū)別
官方文檔在描述 distinct 時(shí)提到:在大多數(shù)情況下 distinct 是特殊的 group by,如下圖所示:
官方文檔地址:https://dev.mysql.com/doc/refman/8.0/en/distinct-optimization.html但二者還是有一些細(xì)微的不同的,比如以下幾個(gè)。
區(qū)別1:查詢結(jié)果集不同
當(dāng)使用 distinct 去重時(shí),查詢結(jié)果集中只有去重列信息,如下圖所示:
當(dāng)你試圖添加非去重字段(查詢)時(shí),SQL 會報(bào)錯如下圖所示:
而使用 group by 排序可以查詢一個(gè)或多個(gè)字段,如下圖所示:
區(qū)別2:使用業(yè)務(wù)場景不同
統(tǒng)計(jì)去重之后的總數(shù)量需要使用 distinct,而統(tǒng)計(jì)分組明細(xì),或在分組明細(xì)的基礎(chǔ)上添加查詢條件時(shí),就得使用 group by 了。使用 distinct 統(tǒng)計(jì)某列去重之后的總數(shù)量:
統(tǒng)計(jì)分組之后數(shù)量大于 2 的文章,就要使用 group by 了,如下圖所示:
區(qū)別3:性能不同
如果去重的字段有索引,那么 group by 和 distinct 都可以使用索引,此情況它們的性能是相同的;而當(dāng)去重的字段沒有索引時(shí),distinct 的性能就會高于 group by,因?yàn)樵?MySQL 8.0 之前,group by 有一個(gè)隱藏的功能會進(jìn)行默認(rèn)的排序,這樣就會觸發(fā) filesort 從而導(dǎo)致查詢性能降低。
總結(jié)
大部分場景下 distinct 是特殊的 group by,但二者也有細(xì)微的區(qū)別,比如它們在查詢結(jié)果集上、使用的具體業(yè)務(wù)場景上,以及性能上都是不同的。