1. 程式人生 > >mysql修改刪除You can't specify target table for update in FROM clause的問題

mysql修改刪除You can't specify target table for update in FROM clause的問題

you div code sql 語句 操作 查詢 重復數 -c sele

表中出現重復數據,需要刪除重復數據,只保留一條

DELETE 
FROM
    crm_participant 
WHERE
    id IN (
SELECT c.id cid FROM crm_participant c WHERE c.parentPhone IN ( SELECT a.parentPhone FROM crm_participant a GROUP BY a.parentPhone HAVING count( a.parentPhone ) > 1 ) AND c.id NOT IN ( SELECT min( b.id ) FROM crm_participant b GROUP BY b.parentPhone HAVING count( b.parentPhone ) > 1 ) ORDER BY
c.parentPhone
)


錯誤信息:

> 1093 - You can‘t specify target table ‘crm_participant‘ for update in FROM clause
> 時間: 0.005s

  

問題分細:
       mysql不允許對同一個表中查出來的數據作為條件,在執行跟新操作。 在一條 sql 語句中不能先查出來部分內容,再同時又對當前表作修改。
       

解決辦法:這個是正確的sql,其實就是對上邊的紅色部分的查詢sql進行了一層包裹。讓查詢出來的信息被一個  select 包裹一下,然後作為條件就可以了

DELETE
FROM crm_participant WHERE id IN ( SELECT v.cid FROM ( SELECT c.id cid FROM crm_participant c WHERE c.parentPhone IN ( SELECT a.parentPhone FROM crm_participant a GROUP BY a.parentPhone HAVING count( a.parentPhone ) > 1 ) AND c.id NOT IN ( SELECT min( b.id ) FROM crm_participant b GROUP BY b.parentPhone HAVING count( b.parentPhone ) > 1
) ORDER BY
c.parentPhone ) v )

mysql修改刪除You can't specify target table for update in FROM clause的問題