Find duplicates or more in Mysql, delete them exce

2019-07-19 02:19发布

问题:

I have a table with rows like id, length, time and some of them are duplicates, where length and time is the same in some rows. I want to delete all copies of the first row submitted.

id | length | time
01 | 255232 | 1242
02 | 255232 | 1242 <- Delete that one

I have this to show all duplicates in table.

SELECT idgarmin_track, length  , time
FROM `80dage_garmin_track`
WHERE length in
       ( SELECT length
         FROM `80dage_garmin_track`
         GROUP
         BY length
         HAVING count(*) > 1 )
ORDER BY idgarmin_track, length, time LIMIT 0,500

回答1:

 DELETE FROM `80dage_garmin_track` t1
 WHERE EXISTS (SELECT 1 from `80dage_garmin_track` t2
          WHERE t1.Length = t2.Length
           AND t1.Time = t2.Time
           AND t1.idgarmin_track > t2.idgarmin_track)


回答2:

If you can take your table offline for a period, then the simplest way is to build a new table containing the data you want and then drop the original table:

create table `80dage_garmin_track_un` like `80dage_garmin_track`;

insert into `80dage_garmin_track_un`
select min(idgarmin_track), length, time 
group by length, time;

rename table `80dage_garmin_track` to old, `80dage_garmin_track_un` to `80dage_garmin_track`;

drop table old;


回答3:

i have the same problem Holsteinkaa, i just use it like this:

 delete from table where id in ( select * from (
    SELECT id FROM table t1
    WHERE EXISTS (SELECT 1 from table t2
      WHERE t1.field = t2.field
       AND t1.id > t2.id
    ) 
 ) as tmp )

i was trying to put this like a comment to Michael Pakhantsov answer but i cant :/ sorry