I have two tables
users table:
id|name
user_relationships
id | user_id | friend_id
and want to ge
You need to join user_relationships with itself, so that two rows with different user_id have the same friend_id
All mutual friends:
select ur1.user_id user1,
ur2.user_id user2,
ur2.friend_id mutual_friend
from user_relationships ur1
JOIN user_relationships ur2 ON ur1.friend_id = ur2.friend_id
where ur1.user_id != ur2.user_id
Join with users table to get the names:
select ur1.user_id user_id1,
u1.name User1,
ur2.user_id user2,
u2.name User2,
ur2.friend_id mutual_friend_id,
u3.name mutual_friend
from user_relationships ur1
JOIN user_relationships ur2 ON ur1.friend_id = ur2.friend_id
JOIN user u1 ON u1.user_id = ur1.user_id
JOIN user u2 ON u1.user_id = ur2.user_id
JOIN user u3 ON ur1.user_id = u3.user_id
where ur1.user_id != ur2.user_id
You can filter for mutual friends for some specific users using ur1.user_id = first_user and ur2.user_id = second_user