Search code examples
phpmysqlrelational-division

What are ways to get mutual friends in a (1, 2) (2, 1) friendship scenario?


I'm developing a website wherein when a person adds another person as a friend, 2 entries are created. Let's say uid 1 adds uid 2 as a friend, the following rows are created in MySQL.

activity_id   uid1 uid2
     1         1     2
     2         2     1

uid 2 becomes friends with uid 3:

activity_id   uid1 uid2
     1         1     2
     2         2     1
     3         2     3
     4         3     2

What are the ways to get the mutual friends between uid 1 and uid 2? I'm using php and MySQL with no PDO experience (for now).

[EDIT] Okay, so I decided to organize/normalize the tables. The relationship only generates 1 row now. which makes the table:

activity_id   uid1 uid2
     1         1     2
     2         2     3

Solution

  • Looking at the table format from your other question, this should do what you want;

    SELECT name FROM users u
    JOIN friends f1
      ON u.uid = f1.uid OR u.uid = f1.fid
    JOIN friends f2
      ON u.uid = f2.uid OR u.uid = f2.fid
    WHERE (f1.uid=1 OR f1.fid=1) AND (f2.uid=3 OR f2.fid=3) 
      AND u.uid<>1 AND u.uid<>3;
    

    Demo here.