2

I'm using this SQL statement to find duplicate records:

  SELECT id, 
         user_id, 
         activity_type_id, 
         source_id, 
         source_type, 
         COUNT(*) AS cnt
    FROM activities
GROUP BY id, user_id, activity_type_id, source_id, source_type
  HAVING COUNT(*) > 1

However, I want to not only find, but delete in the same operation.

3
  • 1
    Delete what, exactly? All of them, all but the earliest or latest? Commented May 25, 2011 at 3:27
  • Related: stackoverflow.com/questions/6103212/… Commented May 25, 2011 at 3:37
  • Is the id field really repeated, as your GROUP BY suggests? Commented May 25, 2011 at 4:51

1 Answer 1

1

delete from activities where id not in (select max(id) from activities group by ....)


Thanks to @OMG Ponies and his other post here is revised solution (but not exactly the same). I assumed here that it does not matter which specific rows are left undeleted. Also the assumption is that id is primary key.

In my example, I just set up one extra column name for testing but it can be easily extended to more columns via GROUP BY clause.

DELETE a FROM activities a 
   LEFT JOIN (SELECT MAX(id) AS id FROM activities GROUP BY name) uniqId 
   ON a.id=uniqId.id WHERE uniqId.id IS NULL;
Sign up to request clarification or add additional context in comments.

8 Comments

If the OP is really GROUPing BY id as the SELECT suggests, then he has duplicated ids, and this won't remove them.
error #1093 - You can't specify target table 'activities' for update in FROM clause
@OMG sorry - I forgot how cranky mysql is. I will play with it and see what comes out. May be some temp table?
@pilcrow If rows are identical in all columns the best shot is to craft something with rownum. But my guess is that id is PK in this case.
@OMG Ponies - revised. Slightly different than your solution but either one is good.
|

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.