mysql - 如何安全地只删除重复的行?

标签 mysql sql

我有一个包含 6.820.483 的表,在这些行之间有很多重复项,我发现运行此查询:

SELECT player_id, match_id, team_id, count(*) 
FROM fixtures
GROUP BY player_id, match_id, team_id
HAVING COUNT(*) > 1

结构示例:

player_id | match_id  | team_id
  19014       2506172    12573
  19014       2506172    12573
  19015       2506172    12573
  19016       2506172    12573
  19016       2506172    12573
  19016       2506172    12573

我怎样才能安全地只删除重复项?在上面的示例中,表格应如下所示:

player_id | match_id  | team_id
  19014       2506172    12573
  19015       2506172    12573
  19016       2506172    12573

表结构:

CREATE TABLE IF NOT EXISTS `swp`.`fixtures` (
  `player_id` INT NOT NULL,
  `match_id` INT NOT NULL,
  `team_id` INT NOT NULL,
  INDEX `player_id_idx` (`player_id` ASC),
  INDEX `match_id_idx` (`match_id` ASC),
  INDEX `FK_team_fixtures_id_idx` (`team_id` ASC),
  CONSTRAINT `FK_player_fixtures_id`
    FOREIGN KEY (`player_id`)
    REFERENCES `swp`.`player` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_match_fixtures_id`
    FOREIGN KEY (`match_id`)
    REFERENCES `swp`.`match` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_team_fixtures_id`
    FOREIGN KEY (`team_id`)
    REFERENCES `swp`.`team` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

最佳答案

我不是 MySQL 期望的人,但你可以试试这个(如果你确定在此期间不会插入新记录):

CREATE TABLE tmp_fixtures
(
  player_id INT NOT NULL,
  match_id  INT NOT NULL,
  team_id   INT NOT NULL
);

SELECT DISTINCT
       player_id,
       match_id,
       team_id
  INTO tmp_fixtures
  FROM fixtures;

TRUNCATE TABLE fixtures;

为了确保不再创建重复记录,您可以执行以下操作:

ALTER TABLE fixtures ADD PRIMARY KEY (player_id, match_id, team_id);

在此之后,重新填充表并清理:

INSERT INTO fixtures (player_id, match_id, team_id)
  SELECT player_id,
         match_id,
         team_id
  FROM   tmp_fixtures;

DROP TABLE tmp_fixtures;

关于mysql - 如何安全地只删除重复的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53396170/

相关文章:

javascript - 使用mysql如何在审计表中插入行?

php - 使用 PDO 和 MySQL 确认记录 INSERT

javascript - 如何选择包含特定单词的 postgreSQL 行

php - 在PHP中如何处理MySQL的外键错误?

SQL 最大参数

mysql - Sequelize.query 执行前的 Nodejs res.status

mysql - 使用单个查询从 mysql 表中删除 csv 文件值

php - 在 codeigniter 中显示具有特定日期的记录

sql - MS Access 更新查询反转查询中的表放置。为什么它有效?

具有表引用自身的 Mysql