SQL 刪除重複資料,重複資料只保留ID最小的行
阿新 • • 發佈:2019-02-02
刪除重複資料,重複資料只保留ID最小的行
DELETE FROM t_customer_comment WHERE id IN ( SELECT * FROM ( SELECT id FROM t_customer_comment WHERE remaintain_order_id IN ( SELECT remaintain_order_id FROM t_customer_comment GROUP BY remaintain_order_id HAVING count(remaintain_order_id) > 1 ORDER BY count(remaintain_order_id) DESC ) AND id NOT IN ( SELECT min(id) FROM t_customer_comment t GROUP BY remaintain_order_id HAVING count(remaintain_order_id) > 1 ORDER BY min(id) ASC ) ) AS ttt )
思路:
1:使用 group by ... having 查找出重複的記錄 a
2:使用select min(id) group by ...having count(...)>1找出重複資料中id最小的記錄 b
3:找出 in a and not in b的資料行,即為需要刪除的資料c;
4:直接使用delete from c 在非ORACEL下會報錯:[Err] 1093 - You can't specify target table 't_customer_comment' for update in FROM clause;此時需要在c的外邊套一層 select * from c as d
5:然後 delete from d ;刪除成功!