MySQL: delete rows returned by subquery

…衆ロ難τιáo~ 提交于 2019-12-25 01:17:59

问题


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.


回答1:


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.




回答2:


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



回答3:


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;



回答4:


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


来源:https://stackoverflow.com/questions/12384107/mysql-delete-rows-returned-by-subquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!