0

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.

2
  • 1
    It looks like your trying to remove all entries where there is a duplicate, not just the duplicate entries. Is that your intention? Commented Sep 12, 2012 at 8:38
  • @podiluska yeah, exactly Commented Sep 12, 2012 at 8:39

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The same issue: You can't specify target table 'r1' for update in FROM clause
MySQL syntax is always surprising. The edited version should work, tested on SQL Fiddle.
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

Comments

0

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;

1 Comment

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON r.id = rr.id'
0
delete from resultitem 
       where id not in (select r.id  
                  from (select r1.id, unique(r1.link) from resultitem r1) as r );

1 Comment

Syntax error: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unique(r.link) from resultitem r )' at line 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.