有没有办法用SQL删除重复项?

时间:2018-06-17 19:59:06

标签: mysql sql mysqli

我有一个名为test_db的表,我想从names列的副本中删除除了一个以外的所有表,这是我的数据库:

ID | Names
---+------
1  | Phil
2  | John
3  | John
4  | James
5  | Phil
6  | Robert

我想保留这个:

ID | Names
---+------
1  | Phil
2  | John
4  | James
6  | Robert

提前致谢。

3 个答案:

答案 0 :(得分:0)

SQL中的规范方法是:

delete from test_db
    where id <> (select min(t2.id) from test_db t2 where t2.name = test_db.name);

在MySQL中,你会这样做:

delete t
    from test_db t join
         (select t2.name, min(t2.id) as min_id
          from test_db t2
          group by t2.name
         ) t2
         on t2.name = t.name
    where t.id > t2.min_id;

答案 1 :(得分:0)

Sql Server中,您可以将查询编写为:

delete T
from test_db T
join (
select Id,
       ROW_NUMBER() over (partition by [Names] order by Id Asc) as rownum
from test_db ) T1
on T.Id = T1.Id
where T1.rownum >1

答案 2 :(得分:0)

delete from test_db where test_db .name 
        in(select * from( select id from test_db where name 
                           in(  select name from test_db
                                 group by name having count(name) > 1  )
                           and id not in (  select min(id) from test_db
                                group by name having count(name) > 1  ))as tableA);
  • tableA的第一个子查询返回查找所有重复的名称。

  • tableA的第二个子查询返回选择一个不想删除的子查询。你可以使用max或min。

  • 使用in获取所有重复的行并使用not in从表A中不想删除的所有重复行中减去

另一种方式

delete from docs where id in(select t1.id from(select id  from docs where name 
  in(  select name from docs 
   group by name having count(name) > 1  )) as t1
  left join (  select id from docs 
   group by name having count(name) > 1  ) as t2
on t1.id=t2.id where t2.id is null);