【发布时间】:2011-08-26 15:13:03
【问题描述】:
我的 MySql 服务器中有一个表,其中包含以下列: ID(int,key),类型(int),名称(varchar)。
由于我的应用程序出错,重复的条目被插入到数据库中,我想删除这些条目,因此每个类型和名称对中只有一行。
关于如何做到这一点的任何想法?
【问题讨论】:
我的 MySql 服务器中有一个表,其中包含以下列: ID(int,key),类型(int),名称(varchar)。
由于我的应用程序出错,重复的条目被插入到数据库中,我想删除这些条目,因此每个类型和名称对中只有一行。
关于如何做到这一点的任何想法?
【问题讨论】:
这取决于您要保留的内容和要删除的内容。由于 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 的“重复”
【讨论】:
id。
delete from s_relations t1 where exists (select 1 from s_relations t2 where t2.source_persona_id = t1.source_persona_id and t2.relation_type = t1.relation_type and t2.message_id = t1.message_id and t2.target_object_id = t1.target_object_id and t1.id > t2.id),但出现以下错误:SQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't1 where exists (select 1 from s_relations t2 ' at line 1
显然首先将此查询更改为选择语句,以确保选择正确的记录进行删除:
delete from table as t1
using table as t2
where t1.type = t2.type and t1.name = t2.name and t1.id > t2.id
【讨论】:
DELETE .. USING。我猜这是 MySQL 特有的?
delete from s_relations as t1 using s_relations as t2 where t2.source_persona_id = t1.source_persona_id and t2.relation_type = t1.relation_type and t2.message_id = t1.message_id and t2.target_object_id = t1.target_object_id and t1.id > t2.id,但出现以下错误:SQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as t1 using s_relations as t2 where t2.source_persona_id = t1.source_persona_i' at line 1
您需要选择 distinct 进入新表,然后删除旧表并重命名新表。但是有很多方法可以做到这一点:
【讨论】:
我最终使用了这篇文章中的解决方案:http://www.justin-cook.com/wp/2006/12/12/remove-duplicate-entries-rows-a-mysql-database-table/
基本上,我已经创建了一个新表,并使用group by 将数据从旧表复制到新表,没有重复
然后我删除了旧表并重命名了新表。
谢谢大家。
【讨论】: