MySQL 刪除表中重複資料,保留最小ID值
阿新 • • 發佈:2019-01-05
使用SQL語句,刪除表中重複的項,保留最小的ID;
在表 tabel 1中,存在大量重複資料,需要刪除重複項,且儲存 ID 為最小的那條記錄。
ID | jzmdid | aac002 | aac003 | yj_month |
10001 | 3002 | -- | -- | 201805 |
10002 | 3002 | -- | -- | 201805 |
10003 | 3003 | -- | -- | 201805 |
10004 | 3004 | -- | -- | 201805 |
[SQL] delete from table1 WHERE jzmdid in ( select jzmdid from table1 where yj_month='201805' GROUP BY jzmdid HAVING COUNT(jzmdid) >1) and id not in ( select min(id) as minid from table1 where yj_month='201805' group by jzmdid having count(jzmdid)>1 ) ; [Err] 1093 - You can't specify target table 'table1' for update in FROM clause
[Err] 1093 - You can't specify target table 'table1' for update in FROM clause
分析:Mysql 中Delete和Update 語句,不允許子查詢中出現update和delete要操作表
解決方法:給子查詢外面再加一個查詢
1、刪除重複記錄,儲存 ID最小的一條
-- 1、刪除重複記錄,儲存Id最小的一條 delete from table1 WHERE yj_month='201805' and jzmdid in ( select * from ( select jzmdid from table1 where yj_month='201805' GROUP BY jzmdid HAVING COUNT( jzmdid ) >1) s ) and id not in ( select minid from ( select min(id) as minid from table1 where yj_month='201805' group by jzmdid having count(jzmdid )>1 ) b) ; 受影響的行: 431250 時間: 106.209s