1

I want to remove the last row because userid and friendwith column is duplicated.

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

thanks.

2
  • why don't you have unique key constraints, instead of trying to delete the duplicates Commented Apr 15, 2012 at 9:06
  • 1
    any logic why the last row??? why not the last but one? Commented Apr 15, 2012 at 9:06

3 Answers 3

2

if you want to keep the latest friendship id then do something like this

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 ;

Or if you want to keep the oldest friendship id then do something like this

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 ;
Sign up to request clarification or add additional context in comments.

Comments

1

You could delete all rows for which another row exists with the same userid and friendswith, but a lower friendshipid. For example:

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.

Comments

0
select friendshipid  ,  userid  , friendwith  , friendshipstatus from table 
group by userid , friendwith  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.