2012-08-23 32 views
1

我已經一路互聯網的結束,我適當卡住。雖然我可以找到部分答案,但我無法修改它以使其正常工作。從MySQL刪除重複的行,其中的值等於什麼

我有一個名爲myfetcher如表:

+-------------+--------------+------+-----+---------+----------------+ 
| Field  | Type   | Null | Key | Default | Extra   | 
+-------------+--------------+------+-----+---------+----------------+ 
| fid_id  | int(11)  | NO | PRI | NULL | auto_increment | 
| linksetid | varchar(200) | NO |  | NULL |    | 
| url   | varchar(200) | NO |  | NULL |    | 
+-------------+--------------+------+-----+---------+----------------+ 

url場有時會包含易受騙的人,但不是刪除所有重複的表,我只需要在現場linksetid等於X

下面的SQL刪除表中的所有重複項(這不是我想要的)...但我想要的只是linksetid中的設置範圍內的重複項。我知道我做錯了什麼,只是不知道它是什麼。

DELETE FROM myfetcher USING myfetcher, myfetcher as vtable 
WHERE (myfetcher.fid>vtable.fid) 
    AND (myfetcher.url=vtable.url) 
    AND (myfetcher.linksetid='$linkuniq') 
+2

只是要清楚,如果你有2排,等於linksetid,你都想要刪除(不只是其中之一)嗎? – HellishHeat

+0

對不起,我只需要一個副本剩餘.. –

回答

2

只刪除linksetid = X的記錄。第一EXISTS檢查情況下,當所有的記錄與linksetid = X那麼只有一個用分鐘(FID)保持。第二個EXISTS檢查情況時有與linksetid <記錄> X然後用linksetid = X的所有記錄都將被刪除:

注:此查詢工作在Oracle或MSSQL。對於MySQL使用下一個解決方法:

DELETE FROM myfetcher 
where (myfetcher.linksetid='$linkuniq') 
     and 
     (
     exists 
     (select t.fid from myfetcher t where 
       t.fid<myfetcher.fid 
       and 
       t.url=myfetcher.url 
       and 
       t.linksetid='$linkuniq') 

     or 

     exists 
     (select t.fid from myfetcher t where 
       t.url=myfetcher.url 
       and 
       t.linksetid<>'$linkuniq') 
     ) 

在MySQL你can't use update/delete command with subquery for the target table。因此對於MySql,您可以使用以下腳本。 SqlFiddle demo

create table to_delete_tmp as 
select fid from myfetcher as tmain 
    where (tmain.linksetid='$linkuniq') 
     and 
     (
     exists 
     (select t.fid from myfetcher t where 
       t.fid<tmain.fid 
       and 
       t.url=tmain.url 
       and 
       t.linksetid='$linkuniq') 

     or 

     exists 
     (select t.fid from myfetcher t where 
       t.url=tmain.url 
       and 
       t.linksetid<>'$linkuniq') 
     ) ; 

delete from myfetcher where myfetcher.fid in (select fid from to_delete_tmp); 

drop table to_delete_tmp; 
+0

的Sql告訴我 「你不能指定目標表‘myfetcher’的更新在FROM子句」 –

+0

請看固定的答案。我添加了一個在MySQL中使用的腳本來避免這個錯誤。 – valex

+0

感謝您的幫助,但你的腳本是不完全做我想要的。它應該刪除一定範圍內的重複並留下剩餘的重複。目前,它只是刪除在給定的[ID]一切都已經存在於表中。 –