我有一张游戏桌,描述如下:
+---------------+-------------+------+-----+---------+----------------+ | 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。不要只在您的数据库上运行删除操作:-)
delete games from games
select * from games