i have a user table
id , username
22 , max
33 , jack
44 , joe
And friends table
id , u1 , u2 , status , reciver
For increasing the speed on reading the friends i’ve decided to add two row to the table for each friendship
so it goes like this
id , u1 , u2 , status , reciver
1 , 22 , 33 , 1 , 22
2 , 33 , 22 , 1 , 22
3 , 22 , 44 , 1 , 22
4 , 44 , 22 , 1 , 22
5 , 22 , 55 , 1 , 22
6 , 55 , 22 , 1 , 22
Now i want to get each user friends and count the mutual friends between these two like facebook
Here is my friends list query :
$profile_id = $current_user->id;
$res = $db->query("
select
u.id as firend_id,
u.username as firend_name,
f.status as firendship_status,
COUNT(f3.u2) as mutual
from friends f
JOIN users u on f.u2 = u.id
LEFT JOIN friends f2 on f.u2 = f2.u1 and f2.u2 != $profile_id
LEFT JOIN friends f3 on f3.u1 = $profile_id AND f3.u2=f2.u2
WHERE f.u1 = $profile_id
group by f2.1
");
echo 'friends list : '
foreach ($res->result() as $r ){
echo $r->firend_name;
echo $r->mutual.' friends';
}
so i check the owner of profile id ($profile_id) against friends.u1 and
join the friends.u2(founded friend) to the users table to get his username and id
the problem is in counting the mutual friends
I join the friends table with it self
on each founded friend
It seems ok on the paper but it returns some weird results
Like if the users has 3 friends and there is no mutual friends it return only one of the 3 friends
!
And if there is mutual friends it shows all of the friends but the mutual friends number is wrong on most cases
there is a problem with group by statement
You can’t do this with only 2 friends tables, you’ll need a third:
friend of $profile_id and the friends of $profile_id
I’ve not tested the following and it works for my sample data – just double check on a larger sample: