2016-04-22 58 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 
)