2012-09-12 141 views
0

我需要刪除表中存在重複link列的行。我試圖運行:MySQL:刪除子查詢返回的行

delete from resultitem 
     where id in (select r.id 
        from resultitem r 
        group by r.link 
        having count(r.id) >1); 

但得到一個錯誤:

ERROR 1093 (HY000): You can't specify target table 'resultitem' for update in FROM clause 

這是可能的,以消除在MySQL子查詢行,而不臨時表? 請指教。

+1

它看起來像你想刪除所有條目,其中有重複的,而不僅僅是重複的條目。這是你的意圖嗎? – podiluska

+0

@podiluska是的,正好 –

回答

4

這應該刪除所有,但最低idlink

delete ri1 
from resultitem as ri1 
inner join 
     resultitem as ri2 
on  ri1.link = ri2.link 
     and ri1.id > ri2.id 

Live example at SQL Fiddle.

要刪除所有重複的鏈接,留下沒有重複的背後,除去and ri1.id > ri2.id

+0

同樣的問題:你不能在FROM子句中指定更新的目標表'r1' –

+0

MySQL語法總是令人驚訝。編輯後的版本應該可以在SQL Fiddle上進行測試。 – Andomar

+0

謝謝,效果很好。 –

0

試試這個...

delete r from resultitem r 
INNER JOIN (
     (select id 
        from resultitem rr 
        group by rr.link 
        having count(rr.id) >1) rr 
ON r.id = rr.id; 
+0

錯誤:您的SQL語法錯誤;檢查與你的MySQL服務器版本相對應的手冊,在'ON r.id = rr.id'附近使用正確的語法' –

+0

缺少正確的paren? –

1
DELETE resultitem 
FROM resultitem 
LEFT OUTER JOIN (
    SELECT MIN(id) as RowId, link 
    FROM resultitem 
    GROUP BY link 
) as KeepRows ON 
    resultitem.id = KeepRows.RowId 
WHERE 
    KeepRows.RowId IS NULL 
0
delete from resultitem 
     where id not in (select r.id 
        from (select r1.id, unique(r1.link) from resultitem r1) as r); 
+1

語法錯誤:'錯誤1064(42000):您的SQL語法有錯誤;請檢查與您的MySQL服務器版本相對應的手冊,以便使用正確的語法,以便在resultitem r)的'唯一(r.link) '附近使用' –