'How do I get friend list from Friends table with counts of friends of my friends

How do I get friend list from Friends table with counts of friends of my friends (Count not of my friends)

Friends table" tbl_users_friends

Field 1: id Field 2: user_id Field 3: friend_user_id

and I need the out put as:

A has following friedns:

x (10) y (2) z (0)

Above is the list of my friends and in parenthesis contains their friends count.

Thanks



Solution 1:[1]

select user_id, count(*) cnt 
   from  Friends 
   where user_id in  
      (select friend_user_id 
         from Friends 
         where user_id = user_id_of_A)
   group by user_id

Solution 2:[2]

Try something like this:

select u.user_id, u.name, count(uf1.id) as num_friends
from tbl_users_friends uf
inner join tbl_users u           on u.user_id = uf.friend_user_id
left  join tbl_users_friends uf1 on uf1.user_id = uf.friend_user_id
where uf.user_id = 1
group by u.user_id, u.name

http://sqlfiddle.com/#!9/10033/1

You need to ajust the users table and column names.

Another solution with a subselect but without group by:

select u.user_id, u.name, (
        select count(*)
        from tbl_users_friends uf1
        where uf1.user_id = uf.friend_user_id
    ) as num_friends
from tbl_users_friends uf
inner join tbl_users u on u.user_id = uf.friend_user_id
where uf.user_id = 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 splash58
Solution 2