Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutual Friend column, select a pair only once

Tags:

sql

I have a table likes, Where ID1 likes ID2

ID1     ID2
1025    1101
1247    1468
1316    1304
1501    1934
1641    1468
1689    1709
1709    1689
1782    1709
1911    1247
1934    1501

so i am select those who like each other, that is example

1501 1934
1934 1501

But i want to select each pair only once, and i am not able to do it. Can anyone point me in the right direction ? its a part of a bigger query, but this part i am not able to do.

Thanks

like image 871
Pheonix Avatar asked Oct 14 '11 15:10

Pheonix


1 Answers

To get a distinct list of all reciprocated likes you can use

SELECT ID1,
       ID2
FROM   likes L1
WHERE  ID1 > ID2
       AND EXISTS(SELECT *
                  FROM   likes L2
                  WHERE  L1.ID1 = L2.ID2
                         AND L1.ID2 = L2.ID1)  
like image 166
Martin Smith Avatar answered Oct 22 '22 19:10

Martin Smith