2013-06-25 21 views
1

刪除重複我有一個表,它看起來像從SQL表

 
col1  col2  col3 
x   y  0.1 
y   x  0.1 
y   z  0.2 
z   y  0.2 

....... 

(X,Y,0.1)等效於(Y,X,0.1),因此它們中的一個必須被移除。

基本上這個表就像一個矩陣。我需要擺脫矩陣對角線上/下的所有條目。該表有100mil條目=>結果將有50mil條目。

回答

3

好吧,如果你知道,這兩個項目都在那裏,你可以這樣做:

delete from t 
    where col1 > col2; 

如果其中一些可能已經失蹤,要保持對方一個:

delete from t 
    where col1 > col2 and 
     exists (select 1 
       from (select 1 
         from t t2 
         where t2.y = t.x and t2.x = t.y 
        ) 
       ) 

「雙」 select是一個黑客繞過MySQL中的限制,你不能直接引用modifie在delete中使用的子查詢中的d表。

編輯:

由於Ypercube指出,加入條款或許是更好的:

delete t 
    from t join 
     t t2 
     on t2.y = t.x and t2.x = t.y and 
      t.y > t.x; 

我居然找到in更容易理解。

+0

您可以在'delete'的'from'子句中使用連接。比雙重嵌套黑客更好。 –

+0

col1和col2是外鍵,不一定每個條目都有「重複」.. – CpS

1

試試多表DELETE

語法並不容易。類似的東西(假設你的表被命名爲tbl):

DELETE tbl FROM tbl, tbl AS t2 
    WHERE tbl.col1 = t2.col2 
     AND tbl.col2 = t2.col1 
     AND tbl.col3 = t2.col3 
     AND tbl.col1 > tbl.col2 
+0

據我瞭解,它會刪除所有行。 – user2407394

+0

@ user2407394我忘了'tbl.col1> tbl.col2'部分。據我測試它,它爲col1,col2交換的每一對刪除一行。保持孤兒線不變。 –

+0

是啊tbl.col1> tbl.col2會做的伎倆..! – user2407394

1

從Sylvain的解決方案應該工作。這是一個使用SubQ的替代方案。

delete from mytable where (col1,col2)in(sel col2,col1 from mytable where col1>col2);