2012-04-15 12 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 duplicate – Dhiraj

+1

なぜ最後の行ですか?なぜ最後の1つですか? –

答えて

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.

関連する問題