MySQL 刪除數(shù)據(jù)庫中重復(fù)數(shù)據(jù)方法小結(jié)
剛開始,根據(jù)我的想法,這個很簡單嘛,上sql語句
delete from zqzrdp where tel in (select min(dpxx_id) from zqzrdp group by tel having count(tel)>1);
執(zhí)行,報錯?。!~
異常意為:你不能指定目標(biāo)表的更新在FROM子句。傻了,MySQL 這樣寫,不行,讓人郁悶。
難倒只能分步操作,蛋疼
以下是網(wǎng)友寫的,同樣是坑爹的代碼,我機器上運行不了。
1. 查詢需要刪除的記錄,會保留一條記錄。
select a.id,a.subject,a.RECEIVER from test1 a left join (select c.subject,c.RECEIVER ,max(c.id) as bid from test1 c where status=0 GROUP BY RECEIVER,SUBJECT having count(1) >1) b on a.id< b.bid where a.subject=b.subject and a.RECEIVER = b.RECEIVER and a.id < b.bid
2. 刪除重復(fù)記錄,只保留一條記錄。注意,subject,RECEIVER 要索引,否則會很慢的。
delete a from test1 a, (select c.subject,c.RECEIVER ,max(c.id) as bid from test1 c where status=0 GROUP BY RECEIVER,SUBJECT having count(1) >1) b where a.subject=b.subject and a.RECEIVER = b.RECEIVER and a.id < b.bid;
3. 查找表中多余的重復(fù)記錄,重復(fù)記錄是根據(jù)單個字段(peopleId)來判斷
select * from people where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
4. 刪除表中多余的重復(fù)記錄,重復(fù)記錄是根據(jù)單個字段(peopleId)來判斷,只留有rowid最小的記錄
delete from people where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1) and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1)
5.刪除表中多余的重復(fù)記錄(多個字段),只留有rowid最小的記錄
delete from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)
看來想偷懶使用一句命令完成這個事好像不太顯示,還是老老實實的分步處理吧,思路先建立復(fù)制一個臨時表,然后對比臨時表內(nèi)的數(shù)據(jù),刪除主表里的數(shù)據(jù)
alter table tableName add autoID int auto_increment not null; create table tmp select min(autoID) as autoID from tableName group by Name,Address; create table tmp2 select tableName.* from tableName,tmp where tableName.autoID = tmp.autoID; drop table tableName; rename table tmp2 to tableName;
相關(guān)文章
教你如何通過日志文件恢復(fù)MySQL數(shù)據(jù)
Binlog日志是二進制日志文件,有兩個作用,一個是增量備份,另一個是主從復(fù)制,即主節(jié)點維護一個binlog日志文件,從節(jié)點從binlog中同步數(shù)據(jù),也可以通過binlog日志來恢復(fù)數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于如何通過日志文件恢復(fù)MySQL數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2022-02-02解決遠(yuǎn)程連接mysql很慢的方法(mysql_connect 打開連接慢)
有次同事提出開發(fā)使用的mysql數(shù)據(jù)庫連接很慢,因為我們的mysql開發(fā)數(shù)據(jù)庫是單獨一臺機器部署的,所以認(rèn)為可能是網(wǎng)絡(luò)連接問題導(dǎo)致的。2011-07-07Keepalived+HAProxy實現(xiàn)MySQL高可用負(fù)載均衡的配置
這篇文章主要介紹了keepalived+haproxy實現(xiàn)MySQL高可用負(fù)載均衡的配置方法,通過這兩個軟件可以有效地使MySQL脫離故障及進行健康檢測,需要的朋友可以參考下2016-02-02MySQL用戶和數(shù)據(jù)權(quán)限管理詳解
這篇文章主要為大家詳細(xì)介紹了MySQL數(shù)據(jù)庫管理中的用戶和數(shù)據(jù)權(quán)限管理,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)MySQL有一定幫助,需要的可以參考一下2022-08-08MySQL使用觸發(fā)器實現(xiàn)數(shù)據(jù)自動更新的應(yīng)用實例
觸發(fā)器是非常常見的自動化數(shù)據(jù)庫操作方式,無論是在數(shù)據(jù)更新、刪除還是需要自動添加一些內(nèi)容到數(shù)據(jù)表上,觸發(fā)器都可以發(fā)揮作用,熟悉 SQL 的基本語法和一些常見的用例,可以幫助你合理地設(shè)置自己的數(shù)據(jù)庫操作流程,2024-01-01