1

I have a table with a structure like this: It has a lot of duplicates, I highlighted two duplicates so you can get an idea. So what I want to do is delete all duplicates and leave only one copy: as you can see it's a table with episodes from TV shows. How can I do this with an SQL command? So basically the command will look for rows with same show_id and same season and episodes and delete all the duplicates except one (There are episodes with 3 copies of the same episode).

THE SCREENSHOT : http://c74.img-up.net/dbdd4e.jpg

1
  • I tried to find a command to do this, but i cant seem to find and I'm not really good at SQL. Commented Aug 30, 2013 at 2:20

3 Answers 3

4

You can delete the duplicates by keeping all records except the one with the lowest id. In MySQL you can do this with a join on delete:

delete t
    from <table> t left outer join
         (select min(id) as minid
          from <table t> t
          group by show_id, season, episode
         ) tokeep
         on t.id = tokeep.minid
    where tokeep.minid is null;
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it by a second!
0

Pretty simple solution of getting a list of ids (1 from each group) and deleting everything else from this question: How to delete duplicate rows with SQL?

DELETE FROM table WHERE id NOT IN
(SELECT MAX(id) FROM table GROUP BY show_id, season, episode);

1 Comment

Updated with your fields
0

You can also let MySql do the work for you adding UNIQE constraint using ALTER IGNORE TABLE ... syntax

ALTER TABLE Table1 ENGINE MyISAM; -- this obviously needed only if your ENGINE is not MyISAM
ALTER IGNORE TABLE Table1 ADD UNIQUE (`show_id`, `season`, `episode`);
ALTER TABLE Table1 ENGINE InnoDB; -- again this is only needed if your ENGINE was other than MyISAM

Here is SQLFiddle demo

Comments

Your Answer

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