【问题标题】:How can I delete duplicate (mixture of two rows) rows in SQL?如何删除 SQL 中的重复(两行混合)行?
【发布时间】:2019-03-12 05:17:23
【问题描述】:

我有一张这样的桌子:

id   c1   c2
1    5    abc
2    5    abc
3    2    xyz
4    2    xyz
5    68   sdf

我想删除 c1 和 c2 相同的行(即 id 为 2 和 4 的行)

编辑:我试过了

ALTER IGNORE TABLE jobs
ADD UNIQUE INDEX idx_name (c1, c2);

但是得到了这个

1834 - 无法从表 'abc' 的外键约束 'xyz' 中的父表中删除行

【问题讨论】:

  • 不重复,见编辑@SamiKuhmonen 抱歉
  • 可以找到一个好的解决方案here
  • 副本中有几种解决方案,而不仅仅是一种。其他的都试过了吗?

标签: mysql sql phpmyadmin


【解决方案1】:

我假设表名是 foobar ,并且 c1 和 c2 不能为空。

这个查询将选择重复的

select d.* from ( select c1 ,c2 , count(*) as cnt , min(id) as mid from foobar         group by c1,c1 ) as e 
       join foobar d on d.c1=e.c1 and d.c2=e.c2 and d.id > e.mid ;

您必须使用要删除的所有 id 的列表创建一个临时表。

create table bad_id_foobar as select d.id  from ( select c1 ,c2 , count(*) as cnt , min(id) as mid from foobar         group by c1,c1 ) as e 
       join foobar d on d.c1=e.c1 and d.c2=e.c2 and d.id > e.mid ; 

这个查询将删除重复的

 delete from foobar           where id in ( select b.id from  bad_id_foobar b );  

【讨论】:

    【解决方案2】:

    这可以通过三个步骤来实现。

    1. 将唯一记录插入 tmp 表(与“jobs”的表结构相同)。

    INSERT INTO tmp (`c1`, `c2`) 
        SELECT c1, c2 
        FROM jobs 
        GROUP BY c1, c2
    1. 删除或重命名“作业”表

    DROP TABLE job

    ALTER TABLE job
    RENAME job_archived
    1. 将“tmp”表重命名为“job”
    ALTER TABLE tmp
    RENAME job
    

    这就是我如何完成这样的任务。可能有更好的方法来做同样的事情......干杯!

    【讨论】:

      猜你喜欢
      • 2015-07-08
      • 2013-08-25
      • 1970-01-01
      • 2020-12-21
      • 2023-02-06
      • 2010-10-10
      相关资源
      最近更新 更多