1. 程式人生 > >【MySQL】常見的業務處理-刪除重複資料

【MySQL】常見的業務處理-刪除重複資料

業務場景

日常工作中我們經常會遇到這樣的場景刪除資料庫中某個表中重複的資料。現在以一個案例驅動。 需求:刪除評論表中同一訂單同一商品的重複評論,只保留最早的一條。 上圖是商品評論表

檢視是否存在重複評論

檢視是否存在對於一訂單同一商品存在重複評論
SELECT order_id, product_id, COUNT(*) 
		FROM product_comment 
	GROUP BY order_id, product_id 
	HAVING COUNT(*)>1;

備份product_comment表
-- 使用LIKE操作完整複製product_comment表的建表語句
CREATE TABLE bak_product_comment_180110 
	LIKE  product_comment;

-- 插入原表的資料
INSERT INTO bak_product_comment_180110 
	SELECT * FROM product_comment;

刪除同一訂單的重複評論

DELETE a FROM product_comment AS a JOIN (
	SELECT order_id, product_id, MIN(comment_id) 
		FROM product_comment GROUP BY order_id, product_id HAVING COUNT(*)>1
) AS b ON a.order_id=b.order_id AND a.product_id=b.product_id AND a.comment_id>b.comment_id;