How can I get friends of friends using mysql and PHP
Currently I need to find friends of friends in my application using PHP and MYSQL
For example: the database structure looks like this. Table name:tbl_friendlist
Ident mem_id friend_id
1 2 1
2 1 2
3 1 3
1 4 1
5 1 8
How can I achieve this
I can get friends
SELECT * FROM tbl_friendlist WHERE mem_id = 1.
Using this, I can get a list of my friends. Now how can I get friends of friends
source to share
So, hack the steps - you want to find all your friends and then you want to find all your friends. These are the two parts of your query (and subquery):
This is how you get a list of all your friends
SELECT friend_id
FROM tbl_friendlist
WHERE f.mem_id = 1
And then you just wrap this in the second part:
SELECT f.friend_id
FROM tbl_friendlist f
WHERE f.mem_id IN (
SELECT f2.friend_id
FROM tbl_friendlist f2
WHERE f2.mem_id = 1
)
You can also add additional filters there, for example:
SELECT DISTINCT f.friend_id
FROM tbl_friendlist f
WHERE f.mem_id IN (
SELECT f2.friend_id
FROM tbl_friendlist f2
WHERE f2.mem_id = 1
) AND f.friend_id <> 1
This means that you will not get duplicates and you will end up on your friends list of friends.
source to share
Hmm, I think something like this might work:
SELECT
f1.friend_id, group_concat( f2.friend_id ) as f_of_f
FROM
tbl_friendlist f1
LEFT JOIN
tbl_friendlist f2 ON ( f1.friend_id = f2.mem_id )
WHERE
f1.mem_id = 1
GROUP BY
f2.mem_id
This will give you the friend ids of the friends as a separate comma value in the f_of_f column.
source to share