在Mysql中,要想刪除一個表中重複的數據,而且只保留一條,該如何作?sql
例如,庫中存在表t_invest_return_record_sum (t),im
有字段id,partner_id,invest_return_time,product_id ,有以下幾條記錄數據
(1,‘b’,'c','d'),(2,‘b’,'c','d'),(5,‘b1’,'c1','d1')查詢
現要根據b,c,d三個字段重複的刪除,留下id最小的一條(最多隻有兩條重複)co
DELETE ta FROM t as ta INNER JOIN (SELECT max(tt.id) id FROM t as tt
GROUP BY tt.b,tt.c,tt.d HAVING COUNT(1)>=2) tb
ON ta.id = tb.id;time
不能直接刪除,如return
DELETE FROM t where id in (SELECT id FROM t as tt
GROUP BY tt.b,tt.c,tt.d HAVING COUNT(1)>=2);
若是重複數超過2個或者不肯定重複數,則須要在子查詢中處理一下
(1,‘b’,'c','d'),(2,‘b’,'c','d'),(3,‘b’,'c','d'),(4,‘b’,'c','d'),(5,‘b1’,'c1','d1')
保留id最小的那條
DELETE tt FROM t_invest_return_record_sum tt INNER JOIN (SELECT a.id FROM t_invest_return_record_sum a INNER JOIN (SELECT t.partner_id,t.invest_return_time,t.product_id FROM t_invest_return_record_sum t GROUP BY t.partner_id,t.invest_return_time,t.product_id HAVING COUNT(1)>=2)t1 ON a.partner_id = t1.partner_id AND a.invest_return_time = t1.invest_return_time AND a.product_id = t1.product_id) t2 ON tt.id = t2.id LEFT JOIN (SELECT min(a.id) id FROM t_invest_return_record_sum a INNER JOIN (SELECT t.partner_id,t.invest_return_time,t.product_id FROM t_invest_return_record_sum t GROUP BY t.partner_id,t.invest_return_time,t.product_id HAVING COUNT(1)>=2)t1 ON a.partner_id = t1.partner_id AND a.invest_return_time = t1.invest_return_time AND a.product_id = t1.product_id) t3 ON tt.id = t3.id WHERE t3.id IS NULL