1. 程式人生 > 其它 >MySQL如何查詢表中重複的資料

MySQL如何查詢表中重複的資料

一、查詢重複記錄
例:查詢員工表裡出現重複姓名的記錄

思路:
1、檢視重複記錄,首先要使用分組函式(group by),再用聚合函式中的計數函式count(name)給姓名列計數,且使用group by 後不可使用*
2、查關鍵字:姓名,以姓名進行分組,看潛在條件:重複,也就是count(name)>1,使用having過濾條件,不可使用where(where子句無法與聚合函式count()一起使用)

方法1

程式碼如下(示例):

方法1
select employee_name,count(*) from employee group by employee_name having count(employee_name)>1;

select employee_name,count(*) from employee group by employee_name having count(employee_name)>1;

方法2:使用別名as

程式碼如下(示例):

方法2
select employee_name,count(*) as c from employee group by employee_name having c>1;

select employee_name,count(*) as c from employee group by employee_name having c>1;

方法3:篩選全部欄位,將符合的資料進行展示

程式碼如下(示例):

方法3,不推薦,執行速度較慢

select * from employee where employee_name in ( select employee_name from employee group by employee_name having count(employee_name)>1);

二、總結
推薦方法2,簡潔且執行速度快;方法3不推薦,需要全部欄位篩選出來,執行速度慢。
————————————————
版權宣告:本文為CSDN博主「晚風吹兒」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/weixin_44688529/article/details/121358920