简体   繁体   English

如何构造一个SQL查询以获取用户之间的共同朋友数?

[英]How to structure a sql query to get number of mutual friends between users?

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. 下面的sql表呈现了用户之间的关系。

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 . 我将如何构造查询以查找userid 4userid 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. 根据您的数据,这将为用户ID 1和4给出结果1,只有一个共同的朋友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. 只给您1和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 它会给你共同的朋友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. 我根据您的查询创建了一个测试表,并组成了一个查询,该查询将显示两个朋友的ID,而他们之间没有共同的朋友。

    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 ;) 询问是否有任何疑问;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM