我有一张这样的桌子:
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'的父表中删除行
答案 0 :(得分:0)
我假设表名是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 );
答案 1 :(得分:0)
这可以通过三个步骤来实现。
INSERT INTO tmp (`c1`, `c2`)
SELECT c1, c2
FROM jobs
GROUP BY c1, c2
DROP TABLE job
ALTER TABLE job
RENAME job_archived
ALTER TABLE tmp
RENAME job
这是我做这样的任务的方式。也许有更好的方法可以做到这一点...干杯!
答案 2 :(得分:0)
简单,删除重复的行并保留最低ID
DELETE t1 FROM jobs j1
NNER JOIN jobs j2
WHERE j1.id > j2.id AND j1.c1 = j2.c1
AND j1.c2 = j2.c2;
然后添加UNIQUE index
以限制重复的条目
CREATE UNIQUE INDEX INDX_restrict_duplicate ON jobs(c1,c2);