id user_id friend_id 134 1 2 132 2 1 82 1 5 48 1 4 28 4 1 10 6 1
i have table of includes above details. this, need 1 row not duplicate 2 fields(user_id
, friend_id
).i.e in first row there user_id = 1
, friend_id = 2
,and in second row user_id = 2
, friend_id = 1
. don't need have both rows same values.
is possible write query following output?
id user_id friend_id 134 1 2 82 1 5 48 1 4 28 4 1 10 6 1
use not exists
return row if switched friendship doesn't exist - higher id (to keep 1 of pairs.)
select t1.* tablename t1 not exists (select * tablename t2 t1.user_id = t2.friend_id , t1.friend_id = t1.user_id , t2.id > t1.id)
and here's alternative version, influenced scaisedge (thanks!):
select * your_table (user_id, friend_id) not in (select friend_id, user_id your_table) or user_id > friend_id order id desc;
the or user_id > friend_id
there keep 1 instance of each pair.
Comments
Post a Comment