MySQL: delete rows returned by subquery

2019-09-15 15:16发布

I need to remove rows where there is a duplicate link column from a table. I'm trying to run:

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

But getting an error:

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

Is this possible to remove rows by subquery in MySQL without a temporary table? Please advise.

4条回答
贪生不怕死
2楼-- · 2019-09-15 15:42
delete from resultitem 
       where id not in (select r.id  
                  from (select r1.id, unique(r1.link) from resultitem r1) as r );
查看更多
Explosion°爆炸
3楼-- · 2019-09-15 15:46

Try this one...

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;
查看更多
\"骚年 ilove
4楼-- · 2019-09-15 15:50

This should delete all but the lowest id per 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.

To remove all duplicate links, leaving none of the duplicates behind, remove the and ri1.id > ri2.id.

查看更多
Bombasti
5楼-- · 2019-09-15 16:00
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
查看更多
登录 后发表回答