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

标签 mysql sql duplicate-removal

我有一个游戏表,描述如下:

+---------------+-------------+------+-----+---------+----------------+
| Field         | Type        | Null | Key | Default | Extra          |
+---------------+-------------+------+-----+---------+----------------+
| id            | int(11)     | NO   | PRI | NULL    | auto_increment |
| date          | date        | NO   |     | NULL    |                |
| time          | time        | NO   |     | NULL    |                |
| hometeam_id   | int(11)     | NO   | MUL | NULL    |                |
| awayteam_id   | int(11)     | NO   | MUL | NULL    |                |
| locationcity  | varchar(30) | NO   |     | NULL    |                |
| locationstate | varchar(20) | NO   |     | NULL    |                |
+---------------+-------------+------+-----+---------+----------------+

但每场比赛在表格中的某处都有重复的条目,因为每场比赛都在两支球队的赛程表中。是否有 sql 语句可用于根据相同的日期、时间、hometeam_id、awayteam_id、locationcity 和 locationstate 字段查看并删除所有重复项?

最佳答案

您应该能够执行相关子查询来删除数据。查找所有重复的行并删除除具有最小 id 的行之外的所有行。对于 MYSQL,需要使用内部连接(功能等同于 EXISTS),如下所示:

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)

要进行测试,请将 delete games from games 替换为 select * from games。不要只是在您的数据库上运行删除 :-)

关于mysql - 如何根据多个字段删除SQL表中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6471463/

相关文章:

mysql - 如何在列表中显示当前月份的项目,其中当前月份的日期在新年的 A 和 B 之间

c# - 使用 LINQ 在多个属性中查找重复项

mongodb - mongo 3在唯一索引上重复 - dropDups

excel - 从excel中的列中删除重复项

php - CSV 数据库输入导致每列占一行

c# - 如何使用 mysql 删除附加行

mysql - 跳过不兼容的/usr/lib64/libmysqlclient.a

mysql - Magento -- "SQLSTATE[23000]: Integrity constraint violation.."客户更新

mysql - SQL 查询中的语法错误

sql - 相当于 BigQuery 标准 SQL 中的 typedef