2011-12-29 127 views
0

我有一个数据库my_table [id,first,second,third]有很多条目,并希望删除条目[first,second,third]的重复数据。如何删除重复的数据

所以没有重复的first并没有重复的second并没有重复的third 只是任何重复的每个然后将被删除。

id first second third 
1 addy  any  robert 
2 addy  kevin steve 
3 jack  ben  adam 

在这里,我将删除重复的first所以删除2 addy kevin steve

+0

你能澄清这个问题吗? – 2011-12-29 19:09:29

+0

这是否意味着[1,1,1,2]将被删除,但[1,3,4,5]不会?那么2将会丢失! – 2011-12-29 19:09:50

+0

我已经添加了一个例子 - 是的,我不在乎如果丢失任何第一行上的任何重复将被删除,即使其他不重复。 – 2011-12-29 19:13:00

回答

1

我会在几个步骤做到这一点。我会首先运行查询获取所有重复项的列表:

select count(id) "count", first from my_table where count > 1 group by first 

这应该(理论上...我不能测试它)返回所有的“第一”有重复的列表。

然后,我将通过每一个“第一次”,在列表循环和运行:

delete from my_table where first = "the_first_in _your_loop" and id not in (select min(id) from my_table where first = "the_first_in _your_loop") 

应该让你开始那!

+0

本条款中的* count *是什么***“其中count> 1组是由第一个”***? – Lion 2011-12-29 19:32:30

+0

count是在select中定义的: select count(id)“count” – 2011-12-29 21:17:29

2

假设表名是T,运行此查询:

Select T1.id, (select count(T2.id) from T as T2 where (T2.id<T1.id) and (T1.first=T2.first or T1.second=T2.second or T1.third=T2.third)) as u from T as T1

如果[U]字段大于0,这意味着您在[first],[second]或[third]中有重新发生的数据。

接下来,你需要删除这些行,用:

Delete from T where id in (...)

+0

你可以做一个操作吗? :-) – 2011-12-29 19:33:08

+0

从T中删除其中id在(从中选择id(选择T1.id,(从T选择count(T2.id)作为T2其中(T2.id 0) – 2011-12-29 19:35:13

+0

你测试过了吗?给我错误。 – 2011-12-29 19:36:31