【问题标题】:How to delete duplicates and leave one row in a table如何删除重复项并在表中保留一行
【发布时间】:2020-07-20 18:27:55
【问题描述】:

我有一张看起来像这样的桌子。我想删除重复项并为每个用户保留一行。我该怎么办?

表格*

id     user 
Thango   1

Thango  1 

Samg     2

Samg     2

结果

id 用户

Thango   1

Samg     2

【问题讨论】:

    标签: mysql sql database duplicates sql-delete


    【解决方案1】:

    对于这个数据集,清空并重新填充表格可能更简单:

    -- deduplicate into a temporary table
    create table mytmp as select distinct id, user from mytable;
    
    -- empty the original table (backup your data first!)
    truncate table mytable;
    
    -- refill the table from the temporary table
    insert into mytable(id, user) select id, user from mytmp;
    
    -- drop the temporary table
    drop table mytemp;
    

    完成此操作后,您可以考虑在表上创建unique 约束以避免进一步重复:

    alter table mytable
        add constraint myconstraint
        unique (id, user);
    

    【讨论】:

      【解决方案2】:

      您使用公用表表达式 (CTE)。为了更好的解释,我建议你看看这个url

      一个可能的解决方案:

      WITH CTE([user], 
      duplicatecount)
      AS (SELECT [user],
                 ROW_NUMBER() OVER(PARTITION BY [user]
                 ORDER BY [id]) AS DuplicateCount
          FROM dbo.[YourDataBase])
      DELETE FROM CTE
      WHERE DuplicateCount > 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-31
        • 1970-01-01
        • 2015-11-22
        • 2013-04-08
        • 2022-11-15
        • 1970-01-01
        • 2014-03-27
        • 1970-01-01
        相关资源
        最近更新 更多