2011-08-26 83 views
2

我在我的MySql服务器中有一个表,其列如下: ID(int,key),type(int),name(varchar)。MySql - 从表中删除重复

由于我的应用程序出现错误,重复的条目被插入到数据库中,我想删除这些条目,所以从每个类型&名称对只会有一行。

有关如何做到这一点的任何想法?

+0

可能重复[什么是重复数据表的最佳方式?](http://stackoverflow.com/questions/2230295/whats-the-best-way-to-dedupe-a-table) –

回答

0

显然,这首先查询更改为select语句,以确保被选中要删除的正确记录:

delete from table as t1 
using table as t2 
where t1.type = t2.type and t1.name = t2.name and t1.id > t2.id 
+0

有趣的语法, '删除..使用'。我想这是MySQL特有的? –

+0

是的,请参阅文档:http://dev.mysql.com/doc/refman/5.0/en/delete.html –

+0

我试着运行脚本:'从s_relations中删除为t1 使用s_relations作为t2 其中t2.source_persona_id = t1.source_persona_id 和t2.relation_type = t1.relation_type 和t2.message_id = t1.message_id 和t2.target_object_id = t1.target_object_id 和t1.id> t2.id',但得到了以下错误:'SQL错误:您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以便在't1 t1 使用s_relations作为t2'时使用正确的语法'其中t2.source_persona_id =第1行't1.source_persona_i' – Ran

1

这取决于你想保留什么,你要删除的内容。由于ID是一个关键,我猜测没有重复的ID,但重复的类型/名称对。因此,这里有一个关于如何删除它们的想法:

delete from my_table t1 
where exists (select 1 
       from my_table t2 
       where t2.type = t1.type 
       and t2.name = t1.name 
       and t2.id < t1.id) 

这将保持“重复”用最低的ID

    and t2.id > t1.id 

这将保持“重复”具有最高ID

+0

您的条件方向相同两次,两者都会保存最低的“id”。 –

+0

哎呀,谢谢! –

+0

我试图运行以下:'从s_relations T1 其中存在删除(从s_relations T2 选择1 其中t2.source_persona_id = t1.source_persona_id 和t2.relation_type = t1.relation_type 和t2.message_id = t1时。 message_id 和t2.target_object_id = t1.target_object_id 和t1.id> t2。ID)',但得到了以下错误:'SQL错误:你在你的SQL语法错误;检查对应于你的MySQL服务器版本使用附近的正确语法手册在行“T1 其中存在的(从s_relations T2 选择1 ” 1' – Ran

0

您需要选择不同的新表格,然后删除旧表格并重命名新表格。但也有很多方法来完成这件事:

What's the best way to dedupe a table?

+0

尼斯的链接,这些都是一些有趣的技术 –