MySQL 去重的 3 種方法?,還有誰不會?!
來源:blog.csdn.net/xienan_ds_zj/article/details/103869048
在使用SQL提數(shù)的時候,常會遇到表內(nèi)有重復值的時候,比如我們想得到 uv (獨立訪客),就需要做去重。
在 MySQL 中通常是使用 distinct 或 group by子句,但在支持窗口函數(shù)的 sql(如Hive SQL、Oracle等等) 中還可以使用 row_number 窗口函數(shù)進行去重。
舉個栗子,現(xiàn)有這樣一張表 task:

備注:
task_id: 任務id;
order_id: 訂單id;
start_time: 開始時間
注意:一個任務對應多條訂單
我們需要求出任務的總數(shù)量,因為 task_id 并非唯一的,所以需要去重:
# distinct
-- 列出 task_id 的所有唯一值(去重后的記錄)-- select distinct task_id-- from Task;-- 任務總數(shù)select count(distinct task_id) task_numfrom Task;
distinct 通常效率較低。它不適合用來展示去重后具體的值,一般與 count 配合用來計算條數(shù)。
distinct 使用中,放在 select 后邊,對后面所有的字段的值統(tǒng)一進行去重。比如distinct后面有兩個字段,那么 1,1 和 1,2 這兩條記錄不是重復值 。
# group by
-- 列出 task_id 的所有唯一值(去重后的記錄,null也是值)-- select task_id-- from Task-- group by task_id;-- 任務總數(shù)select count(task_id) task_numfrom (select task_idfrom Taskgroup by task_id) tmp;
# row_number
row_number 是窗口函數(shù),語法如下:
row_number() over (partition by <用于分組的字段名> order by <用于組內(nèi)排序的字段名>)其中 partition by 部分可省略。
-- 在支持窗口函數(shù)的 sql 中使用select count(case when rn=1 then task_id else null end) task_numfrom (select task_id, row_number() over (partition by task_id order by start_time) rnfrom Task) tmp;
此外,再借助一個表 test 來理理 distinct 和 group by 在去重中的使用:

-- 下方的分號;用來分隔行select distinct user_idfrom Test; -- 返回 1; 2select distinct user_id, user_typefrom Test; -- 返回1, 1; 1, 2; 2, 1select user_idfrom Testgroup by user_id; -- 返回1; 2select user_id, user_typefrom Testgroup by user_id, user_type; -- 返回1, 1; 1, 2; 2, 1select user_id, user_typefrom Testgroup by user_id;-- Hive、Oracle等會報錯,mysql可以這樣寫。-- 返回1, 1 或 1, 2 ; 2, 1(共兩行)。只會對group by后面的字段去重,就是說最后返回的記錄數(shù)等于上一段sql的記錄數(shù),即2條-- 沒有放在group by 后面但是在select中放了的字段,只會返回一條記錄(好像通常是第一條,應該是沒有規(guī)律的)
評論
圖片
表情
