2012-04-15 74 views
1

我想刪除最後一行,因爲userid和friendwith列是重複的。從數據庫表中刪除具有多個重複列的行

friendshipid userid friendwith friendshipstatus 
183    24  102   4 
151    24  52   2 
155    24  66   2 
179    24  66   2 

謝謝。

+0

爲什麼你沒有獨特的關鍵約束,而不是試圖刪除e複製 – Dhiraj 2012-04-15 09:06:03

+1

任何邏輯爲什麼最後一行?爲什麼不是最後一個? – 2012-04-15 09:06:18

回答

3
如果你想保持最新的友誼ID

然後做這樣的事情

CREATE TABLE temp_table AS (SELECT * FROM table); 
DELETE FROM table WHERE friendshipid NOT IN (SELECT friendshipid FROM (SELECT * FROM temp_table ORDER BY friendshipid DESC) as temp_table GROUP BY userid, friendwith); 
DROP TABLE temp_table ; 

或者,如果你想保留最古老的友誼ID,然後像做這

CREATE TABLE temp_table AS (SELECT * FROM table); 
DELETE FROM table WHERE friendshipid NOT IN (SELECT friendshipid FROM (SELECT * FROM temp_table ORDER BY friendshipid ASC) as temp_table GROUP BY userid, friendwith); 
DROP TABLE temp_table ; 
0
select friendshipid , userid , friendwith , friendshipstatus from table 
group by userid , friendwith 
1

你可以刪除其另一行具有相同的useridfriendswith存在的所有行,但較低的friendshipid。例如:

delete dup 
from YourTable as dup 
join YourTable orig 
on  orig.userid = dup.userid 
     and orig.friendwith = dup.friendwith 
     and orig.friendshipid < dup.friendshipid 

Example at SQL Fiddle.

相關問題