2015-11-08 56 views
0

我想根據客戶電話號碼從表中刪除重複項。下面正確內選擇查詢,選擇,我需要刪除所有重複的記錄,但是outter刪除查詢生成以下錯誤:查詢刪除重複項會產生錯誤

You can't specify target table 'customers' for update in FROM clause 

查詢:

DELETE FROM customers WHERE id IN (SELECT id from customers GROUP BY phone HAVING COUNT(phone) > 1) 

回答

0

updatedelete語句,通常不能引用被修改的表。一個簡單的解決方案是使用一個join

DELETE c 
    FROM customers c JOIN 
     (SELECT phone, COUNT(*) as cnt 
      FROM customers c 
      GROUP BY phone 
     ) p 
     ON c.phone = p.phone AND cnt > 1; 

請注意,此刪除表中的所有重複。通常情況下,你想保留其中之一:

DELETE c 
    FROM customers c LEFT JOIN 
     (SELECT phone, MIN(id) as minid 
      FROM customers c 
      GROUP BY phone 
     ) p 
     ON c.id = p.minid 
    WHERE p.phone IS NULL; 
+0

感謝您的答覆。還嘗試了以下,'刪除客戶 GROUP BY電話HAVING COUNT(電話)> 1',任何想法爲什麼這樣也行不通? – AnchovyLegend

+0

您的第一個解決方案選擇的方式不僅僅是重複的電話號碼,第二個解決方案我不是 – AnchovyLegend