【问题标题】:sql: remove dupliacte rows except one with limitsql:删除重复行,但有限制的行除外
【发布时间】:2018-02-24 11:07:41
【问题描述】:

这是我的 sql 查询,用于删除重复行,但有限制的行除外

DELETE n1 FROM v_news n1, v_news n2 WHERE n1.`id` > n2.`id` AND n1.`url` = n2.`url` ORDER BY n2.`id` LIMIT 100

但我得到这样的错误:

MySQL said: Documentation

#1064 - 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 'ORDER BY n2.`id` LIMIT 100' at line 1

我哪里错了?

提前致谢。

【问题讨论】:

  • 我猜在删除查询顺序和限制是适用的。
  • 可以删除“order by”。但必须有一个限度。因为行数非常多。
  • 在删除操作中使用 orderby 关键字会出错。
  • 使用您想要的语法无法实现您想要做的事情。我建议您用样本数据和期望的结果问另一个问题。
  • 仅供参考:我对 MySQL 不够熟悉,无法回答;但在 SQL Server 中,您可以像这样限制删除的行数:stackoverflow.com/a/8956164/361842。提供任何提示的情况。

标签: mysql sql duplicates rows


【解决方案1】:

对于删除查询,无需包含order bylimit。所以只需删除这两个并尝试如下所示,

DELETE n1 FROM v_news n1, v_news n2 WHERE n1.`id` > n2.`id` AND n1.`url` = n2.`url`

【讨论】:

  • 我认为重点是@Jake 只想删除最多 100 行(不知道为什么,但大概有一个潜在的逻辑)。
  • 谢谢,我使用了限制,因为我的表中有几百万行,服务器无法完成请求。
  • 这样你就可以在for 循环中使用删除命令。它可能会起作用
【解决方案2】:

正如documentation 解释的那样:

您可以在DELETE 语句中指定多个表来删除行 根据WHERE 中的条件从一个或多个表中 条款。您不能在多表DELETE 中使用ORDER BYLIMIT

换句话说,您的DELETE 引用了两个表(嗯,同一个表两次),因此它被认为是多表删除。不允许使用 ORDER BYLIMIT

注意:您应该使用JOIN 而不是逗号来指定表格。

【讨论】:

    【解决方案3】:

    这种方法可能有效:

    --use a temp table record the ids of the records you wish to delete
    create temporary table if not exists newsIdsToDelete 
    (
        Id bigint
        , PRIMARY KEY (id)
    ) ENGINE=MEMORY;
    
    --populate that table with the IDs from your original query
    select n1.`Id` 
    into newsIdsToDelete
    from v_news n1
    inner join v_news n2 
    on n2.`id` < n1.`id` 
    and n2.`url` = n1.`url` 
    order by n2.`id` 
    limit 100;
    
    --delete those records where the id's in the list of ids to be deleted
    delete v_news 
    where `Id` in (
        select `Id` 
        from newsIdsToDelete
    );
    
    --clean up the temporary table
    drop temporary table if exists newsIdsToDelete;
    

    (我没有 MySql,而且我对那个数据库的了解非常多,所以请在使用前在安全的地方进行测试)。

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 2019-10-30
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      相关资源
      最近更新 更多