【问题标题】:MySql - delete duplications from tableMySql - 从表中删除重复项
【发布时间】:2011-08-26 15:13:03
【问题描述】:

我的 MySql 服务器中有一个表,其中包含以下列: ID(int,key),类型(int),名称(varchar)。

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

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

【问题讨论】:

标签: mysql sql


【解决方案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 的“重复”

【讨论】:

  • 条件相同的方向两次,都会保存最低的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 &gt; 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
【解决方案2】:

显然首先将此查询更改为选择语句,以确保选择正确的记录进行删除:

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 &gt; 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
【解决方案3】:

您需要选择 distinct 进入新表,然后删除旧表并重命名新表。但是有很多方法可以做到这一点:

What's the best way to dedupe a table?

【讨论】:

  • 不错的链接,这些是一些有趣的技术
【解决方案4】:

我最终使用了这篇文章中的解决方案:http://www.justin-cook.com/wp/2006/12/12/remove-duplicate-entries-rows-a-mysql-database-table/

基本上,我已经创建了一个新表,并使用group by 将数据从旧表复制到新表,没有重复 然后我删除了旧表并重命名了新表。

谢谢大家。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 2010-09-19
    相关资源
    最近更新 更多