I am busy trying to create a query that returns the number of mutual friends between users in a userlist. I have tried a few but they haven't been working as I had hoped, here is one of the queries I have tried
query("SELECT * FROM userlist WHERE userid = '$userid' AND status ='friend' AND friendid != '$userid' ");
the sql table below renders the relationships between users.
userid | friendid | type | status |
-----------------------------------
1 |2 | buddy | friend |
-----------------------------------
1 |3 | buddy | friend |
-----------------------------------
2 |3 | buddy | friend |
-----------------------------------
3 |2 | buddy | friend |
-----------------------------------
4 |2 | buddy | friend |
-----------------------------------
3 |1 | buddy | friend |
-----------------------------------
2 |4 | buddy | friend |
------------------------------------
How would I structure a query to find the number of mutual friends between userid 4
and userid 1
.
Thanks.
I think this will help, Please note that, here i do not have used condition of "status", you can modify this query as per your requirement.
SELECT count(*) FROM userlist as a
INNER JOIN userlist as b
ON(b.friendid=a.friendid and b.userid=4 and b.friendid!=1)
WHERE a.userid=1 and b.friendid!=4
This will return number of mutual friends.
As per your data this will give result 1 as for user ID 1 and 4 there is only one mutual friend 2.
Select friendid
FROM userlist as F
WHERE userid = 1
Select friendid
FROM userlist as S
WHERE userid = 4
Select Distinct *
From F Join S
ON F.friendid = S.friendid
Would give you only the mutual friends of 1 and 4.
SELECT Distinct a.friendid as mutual_friend
FROM user_list AS a
JOIN user_list b ON a.friendid = b.friendid
WHERE (a.userid =1 or a.friendid=1)
AND (b.userid =2 or b.friendid=2)
It would give you the Mutual friends id
I made a test Table upon your query and made up a query which will show ids of two friends and no of mutual friends between them.
SELECT
a.ID as Person1, b.ID as Person2, COUNT(a.FriendID) as NoOfMutualFriends
FROM
Friends a INNER JOIN Friends b
ON a.FriendID = b.FriendID
WHERE a.ID <> b.ID //other filters can be used here
GROUP BY a.ID, b.ID
ORDER BY a.ID
Ask if any Doubts ;)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.