删除重复数据,重复数据只保留ID最小的行
DELETEFROMt_customer_commentWHEREid IN (SELECT*FROM(SELECTidFROMt_customer_commentWHEREremaintain_order_id IN (SELECTremaintain_order_idFROMt_customer_commentGROUP BYremaintain_order_idHAVINGcount(remaintain_order_id) > 1ORDER BYcount(remaintain_order_id) DESC)AND id NOT IN (SELECTmin(id)FROMt_customer_comment tGROUP BYremaintain_order_idHAVINGcount(remaintain_order_id) > 1ORDER BYmin(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 ;删除成功!