【问题标题】:Delete Duplicate records and keep one in MYSQL version 5.7 ( Table with out primary key)在 MYSQL 5.7 版本中删除重复记录并保留一个(没有主键的表)
【发布时间】:2023-02-13 23:04:22
【问题描述】:

我们的项目表中有一些重复的条目并试图删除它们但需要其中一个

表:项目(无主键

ItemNumber,lastModifiedDate
10056,'2020-10-19'
10056,'2020-10-19'
10057,'2020-10-19'
10057,'2020-10-20'

预期输出:

ItemNumber,lastModifiedDate
10056,'2020-10-19'
10057,'2020-10-20'

我在下面尝试过:

delete from Items where (ItemNumber,LastModifiedDate) not in
(
SELECT
ItemNumber,max(LastModifiedDate) LastModifiedDate
FROM
(select * from Items ) Items
GROUP BY
ItemNumber
);

我们可以在 Mysql V8 中使用 ROW_NUMBER() windows 函数来完成,但该功能在 5.7 中不可用,我现在无法升级数据库。

提前致谢

【问题讨论】:

    标签: mysql duplicates


    【解决方案1】:

    您的问题实际上很棘手,因为您的重复记录在各个方面都完全相同。这里的一种方法是过滤掉临时表中的重复项。然后截断当前表并使用过滤后的数据填充它。

    CREATE TEMPORARY TABLE ItemsTemp AS (
        SELECT ItemNumber, MAX(lastModifiedDate) AS lastModifiedDate
        FROM Items
        GROUP BY ItemNumber
    )
    
    TRUNCATE TABLE Items;  -- remove all data in Items
    
    -- repopulate Items using non duplicate data
    INSERT INTO Items (ItemNumber, lastModifiedDate)
    SELECT ItemNumber, lastModifiedDate
    FROM ItemsTemp;
    
    DROP TABLE ItemsTemp;  -- drop the temporary table
    

    【讨论】:

    • OP需要为每个ItemNumber保存一份MAX(lastModifiedDate)
    【解决方案2】:

    我以另一种方式找到了答案。

    alter table add id column with auto increment by 1, 然后你得到了区分器,按必填字段分组,保留 min(id) 记录并删除剩余的重复项。

    【讨论】:

      猜你喜欢
      • 2015-09-27
      • 1970-01-01
      • 2021-11-16
      • 2012-04-12
      • 2013-12-30
      • 2016-02-12
      • 2010-11-02
      • 1970-01-01
      相关资源
      最近更新 更多