您好,登錄后才能下訂單哦!
這篇文章主要講解了“mysql查找刪除重復數據并只保留一條的方法”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“mysql查找刪除重復數據并只保留一條的方法”吧!
有這樣一張表,表數據及結果如下:
school_id | school_name | total_student | test_takers |
1239 | Abraham Lincoln High School | 55 | 50 |
1240 | Abraham Lincoln High School | 70 | 35 |
1241 | Acalanes High School | 120 | 89 |
1242 | Academy Of The Canyons | 30 | 30 |
1243 | Agoura High School | 89 | 40 |
1244 | Agoura High School | 100 | 50 |
我們可以看出,school_name的字段值有重復數據(Abraham Lincoln High School 和Agoura High School分別出現兩次),那么如何刪除這兩條數據,從而只讓這兩個數值出現一次呢? 具體實現方法如下:
1、刪除重復記錄,保存Id最小的一條
delete FROM `test` WHERE `school_name` in (SELECT `school_name` FROM `test` GROUP BY `school_name` HAVING COUNT( * ) >1) and school_id not in (select min(school_id) from test group by school_id having count(* )>1)
先使用GROUP BY having語法查詢出重復的數據,然后刪除重復數據并保留school_id最小的一條.
2、刪除重復記錄,保存Id最大的一條
delete FROM `test` WHERE `school_name` in (SELECT `school_name` FROM `test` GROUP BY `school_name` HAVING COUNT( * ) >1) and school_id not in (select max(school_id) from test group by school_id having count(* )>1)
原理和上面一樣。
感謝各位的閱讀,以上就是“mysql查找刪除重復數據并只保留一條的方法”的內容了,經過本文的學習后,相信大家對mysql查找刪除重復數據并只保留一條的方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。