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

Marc Delisle
  • 8,879
  • 3
  • 29
  • 29
  • I tried to find a command to do this, but i cant seem to find and I'm not really good at SQL. –  Aug 30 '13 at 02:20

3 Answers3

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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
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);
Community
  • 1
  • 1
Matthew
  • 9,851
  • 4
  • 46
  • 77
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

peterm
  • 91,357
  • 15
  • 148
  • 157