2016-04-22 62 views
0

我有一个表(数百万记录)与唯一索引(dataid,url)。该表是这样的:更新与重复记录的sql查询

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'值的记录。我如何去做这件事?

+1

MySQL或SQL Server?不同的产品,类似的SQL,但有一些差异。 – jarlh

+0

您可以添加更多示例数据和预期结果吗?现在只有两行,具有相同的dataid。 – jarlh

+0

替换前缀为http和www的网址,例如'http:// www.abc.de'将产生'https:// www.www.abc.de' ......只是为了记住它。首先检查是否存在这种情况,如果存在,则将所有'http:// www.'更改为'http://',然后按照您的意愿使用'https:// www.'替换网络完成。 – MrSimpleMind

回答

0
delete 
    from table a 
    join table b on a.dataid = b.dataid 
where 
    a.dataid = 230 and a.id > b.id; 

尝试一下

0

这将发现,应予以删除

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.') 
0
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.'); 
0

首先您应该删除重复项。 此查询应该会对您有所帮助:

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