Facebook mutual friends SQL

In case someone does not want to bother to get the mutual friends using FQL. This applies also in SQL if in your database have declared a table named let’s say “friend” and it has two columns uid1 and uid2. Of course in my case user id “1” and user id “5” are just an example




SELECT f1.uid2


FROM friend AS f1


WHERE f1.uid1=1


AND EXISTS


(


	SELECT *


	FROM friend AS f2


	WHERE f2.uid1=5


	AND f1.uid2=f2.uid2


);



But what happens if the person has only one or two common friends

Within all the friends of this person is not difficult to find some friends of them who are common with your friends.

In other words now we simple need the mutual friends with all the people in the friend list of this person.

But since the target person is the user id "4", we want to find who of his/her friends have some common friends with our friends. I mean we do not want to get a list with some of our friends. We would like to get a list of friends of user id "4" with whom we are connected one level away: with each one of them we have at least one mutual friend.

The modification is pretty simple as you can see:




SELECT f1.uid2


FROM friend AS f1


WHERE f1.uid1=4


AND EXISTS


(


	SELECT *


	FROM friend AS f2


	WHERE f2.uid1 IN


	(


		SELECT f3.uid1


		FROM friend AS f3


		WHERE f3.uid2 = 1


	)


	AND f1.uid2=f2.uid2


);



As you may have guessed in this version the user id “4” and user id “1” cannot tranpose their positions inside the code. So user id “4” is the target person and user id “1” is yourself :)

Thank you for the post, it was helpful!