1. 程式人生 > >mysql刪除資料表中重複記錄保留一條

mysql刪除資料表中重複記錄保留一條

刪除資料庫中重複的記錄由兩種形式:
第一種是資料表中所有的欄位都重複,第二種是資料庫中部分欄位重複
這裡針對第二種情況重複:

delete from app_user_verify where id not in (select a.id from (select MAX(id) as id from app_user_verify  GROUP by code_type,telephone,status) a)

如果出現You can’t specify target table for update in FROM clause錯誤的意思是說,不能先select出同一表中的某些值,再update這個表(在同一語句中)
在加上一層select 即可

delete from app_user_verify where id not in (select b.id from (select a.id from (select MAX(id) as id from app_user_verify GROUP BY code_type,telephone,status) a) b) 

其中code_type,telephone,status是重複的欄位
這種一條sql語句形式如果資料量很大刪除會很慢,可以分別執行sql語句,然後用php將他們整合即可
參考文章