【问题标题】:Update query in sql with duplicate records使用重复记录更新sql中的查询
【发布时间】:2016-08-15 16:58:51
【问题描述】:

我有一个表(数百万条记录),其中包含 (dataid,url) 的唯一索引。该表如下所示:

id  dataid url
1   230    https://www.example.com/123
3   230    http://example.com/123

我无法运行查询

UPDATE table_name SET url = REPLACE(url, 'http://', 'https://www.')

因为存在重复和违反唯一键约束。在这种情况下,我想删除具有最大“id”值的记录。我该怎么办?

【问题讨论】:

  • MySQL 还是 SQL Server?不同的产品,相似的SQL,但有些不同。
  • 您能否添加更多示例数据,以及预期的结果?现在只有两行,具有相同的 dataid。
  • 替换以 http 和 www 为前缀的 url,例如http://www.abc.de 将导致 https://www.www.abc.de ... 记住它。首先检查您是否有这种情况,如果它们存在然后将所有http://www. 更改为http://,然后使用https://www. replacemenet 完成。
  • @jarlh MySQL...我无法添加许多链接.. id dataid url 1 230 example.com/123 3 230 example.com/123 4 231 example.com/1234 预期输出 id dataid url 1 230 @987654324 @ 4 231 example.com/1234
  • @MrSimpleMind 谢谢你的意见。但幸运的是,表格中没有这样的条目。

标签: mysql sql mysql-workbench mysql-error-1062


【解决方案1】:
delete 
    from table a 
    join table b on a.dataid = b.dataid 
where 
    a.dataid = 230 and a.id > b.id;

试试看

【讨论】:

    【解决方案2】:

    这将找出应该删除的行

    select max(id), REPLACE(url, 'http://', 'https://www.') as url from table
    group by REPLACE(url, 'http://', 'https://www.') 
    having count(*)>1
    

    这将删除它们

    delete t1 from table as t1 inner join
    (
    select max(id), REPLACE(url, 'http://', 'https://www.') as url from table
    group by REPLACE(url, 'http://', 'https://www.') 
    having count(*)>1
    ) as t2 on t1.id=t2.id
    

    现在更新您的数据

    UPDATE table_name SET url = REPLACE(url, 'http://', 'https://www.')
    

    【讨论】:

      【解决方案3】:
      delete tst
      where id in (select max(id)
                   from tst
                   group by dataid, REPLACE(url, 'http://', 'https://www.')
                   having count(*) = 2);
      
      UPDATE tst SET url = REPLACE(url, 'http://', 'https://www.');
      

      【讨论】:

        【解决方案4】:

        首先您应该删除重复项。 这个查询应该可以帮助你:

        delete from 
        table_name 
        where id in (
           select max(id)
           from table_name 
           group by REPLACE(url, 'http://', 'https://www.')
           having count(*) > 1
        )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多