如何删除重复数据
业务场景:删除评论表中对同一订单同一商品的重复评论,只保留最早的一条。
- 查看是否存在对于同一订单同一商品的重复评论。
SELECT order_id,product_id,COUNT(*) FROM product_comment GROUP BY order_id,product_id HAVING COUNT(*)>1;
- 备份product_comment表。
CREATE TABLE bak_product_comment_18051801 LIKE product_comment;
INSERT INTO bak_product_comment_18051801 SELECT * FROM product_comment;
- 删除同一订单的重复评论。
DELETE a FROM product_comment a JOIN( SELECT order_id,product_id,MIN(comment_id) AS comment_id FROM product_comment GROUP BY order_id,product_id HAVING COUNT(*)>=2 ) b ON a.order_id=b.order_id AND a.product_id=b.product_id AND a.comment_id>b.comment_id