且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据多个字段删除SQL表中的重复项

更新时间:2023-11-09 21:19:10

您应该可以执行相关子查询来删除数据。查找重复的所有行,并删除除ID以外的所有行。对于MYSQL,需要使用内部连接(功能相当于EXISTS),如下所示:

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)

要测试,请将删除游戏从 with select * from games 。不要只在你的数据库中运行删除: - )

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