Mysql:如何删除违反UNIQUE约束的所有重复项

时间:2018-05-21 08:50:27

标签: mysql

我想在表中添加一个UNIQUE索引,如下所示:

ALTER TABLE `mytable` ADD UNIQUE `myunique_name`(`first`, `second`, `third`);

Mysql回复:

Duplicate entry '1-2-3' for key 'myunique_name'

我确信这种组合只是违反约束条件的千分之一。

在这种特殊情况下,我确信在三个指定列中包含相同值的所有行在其他相关字段中也包含相同的数据(主要索引当然不同,但是无关紧要),因此所有重复项可以删除。

有没有办法删除所有重复的条目但保留一个(保留哪个主键并不重要),以便添加唯一索引?

1 个答案:

答案 0 :(得分:0)

CREATE TEMPORARY TABLE IF NOT EXISTS MyTable engine=memory 
select 1 as id, 1 col1,1 col2,1 col3
union all
select 2 as id, 2 col1,2 col2,2 col3
union all
select 3 as id, 3 col1,3 col2,3 col3
union all
select 4 as id, 4 col1,4 col2,4 col3
union all
select 5 as id, 1 col1,1 col2,1 col3
union all
select 6 as id, 2 col1,2 col2,2 col3


CREATE TEMPORARY TABLE IF NOT EXISTS MyDuplicateTableWithCount engine=memory 
select col1  , col2  , col3, count(*) Count_1
from MyTable
group by col1  , col2  , col3
having count(*)>1


  select a.* from  MyTable a
    inner join 
    (select col1  , col2  , col3
    from MyDuplicateTableWithCount
     ) b
     on a.col1 =b.col1 and a.col2 =b.col2 and  a.col3 =b.col3
    order by a.id

获取重复ID后,将删除查询指定为重复ID为

delete from myTable where id in (5,6)

还可以使用上面的myTable

进行以下查询
CREATE TEMPORARY TABLE IF NOT EXISTS MyTable2 engine=memory 
 SELECT MIN(id) as id, Col1, Col2, Col3 
   FROM MyTable 
   GROUP BY Col1, Col2, Col3

DELETE a FROM MyTable as a
LEFT  JOIN (
   SELECT * from MyTable2
) as b ON
   b.id = a.id
WHERE
   b.id IS NULL