How to delete duplicates in SQL table based on multiple fields

后端 未结 9 518
星月不相逢
星月不相逢 2020-12-04 14:58

I have a table of games, which is described as follows:

+---------------+-------------+------+-----+---------+----------------+
| Field         | Type                


        
9条回答
  •  余生分开走
    2020-12-04 15:28

    You should be able to do a correlated subquery to delete the data. Find all rows that are duplicates and delete all but the one with the smallest id. For MYSQL, an inner join (functional equivalent of EXISTS) needs to be used, like so:

    delete games from games inner join 
        (select  min(id) minid, date, time,
                 hometeam_id, awayteam_id, locationcity, locationstate
         from games 
         group by date, time, hometeam_id, 
                  awayteam_id, locationcity, locationstate
         having count(1) > 1) as duplicates
       on (duplicates.date = games.date
       and duplicates.time = games.time
       and duplicates.hometeam_id = games.hometeam_id
       and duplicates.awayteam_id = games.awayteam_id
       and duplicates.locationcity = games.locationcity
       and duplicates.locationstate = games.locationstate
       and duplicates.minid <> games.id)
    

    To test, replace delete games from games with select * from games. Don't just run a delete on your DB :-)

提交回复
热议问题