gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:33:54 25 4
gpt4 key购买 nike

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

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

Mysql 响应:

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

我确信这个组合只是违反约束的数千个组合中的一个。

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

有没有办法删除所有重复条目但保留一个(无论保留哪个主键)以便可以添加唯一索引?

最佳答案

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

关于Mysql:如何删除所有违反UNIQUE约束的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50445107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com