MySQL:删除子查询返回的行

时间:2012-09-12 08:31:53

标签: mysql sql subquery

我需要从表中删除存在重复link列的行。我正试图跑:

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中的子查询删除行? 请指教。

4 个答案:

答案 0 :(得分:4)

这应删除除id以外的所有link以外的所有内容:

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

答案 1 :(得分: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

答案 2 :(得分: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;

答案 3 :(得分:0)

delete from resultitem 
       where id not in (select r.id  
                  from (select r1.id, unique(r1.link) from resultitem r1) as r );