简体   繁体   English

MYSQL-计算并计算共同的朋友

[英]MYSQL - Work out & Count mutual friends

I'm having a little bit of a brain fart this evening trying to work out my logic. 今晚我有点脑子屁,想弄清楚我的逻辑。 I need to count how many friends a person shares with one user. 我需要计算一个人与一个用户共享多少个朋友。 (Mutual friends) (共同的朋友)

I have a table with a User ID and also the User ID of a friend, an example of my layout is below: 我有一个带有用户ID和朋友的用户ID的表,下面是我的布局示例:

First result meaning user1 is friends with user 2 第一个结果表示user1是与user 2的朋友

[ID] - [FriendsID]
1-2
1-3
1-4
1-15
2-1
2-4
3-1
3-4
4-1
4-2
4-3
4-15
5-15
15-1
15-5
15-4

When my PHP Page loads, It will load the friends list for that user for example, User1. 当我的PHP页面加载时,它将加载该用户的好友列表,例如User1。 This will return the “FriendID” of (2,3,4.15) 这将返回(2,3,4.15)的“ FriendID”

I then need to work out how many mutual friends people have with user: 1 So for example, 然后,我需要计算出与用户有多少个共同的朋友:1例如,

1 is friends with 2,3,4
2 is friends with 1,4
3 is friends with 1,4,15

This would mean that “2” shares ONE mutual friend with 1
This would mean that “3” shares TWO mutual friend with 1

and so on 等等

My output needs to be [FriendID] [Count] 我的输出必须是[FriendID] [Count]

Friend ID being the friend 好友ID为好友

Count being how many friends in common with userID 1 计算与userID 1共有多少个朋友

(Example data manually written out) (示例数据手动写出)

You can do this using a self-join on the friendsid column: 您可以在friendsid列上使用自friendsid来完成此操作:

select t1.id, t2.id, count(*) as num_mutual_friends
from table t1 join
     table t2
     on t1.friendsid = t2.friendsid and t1.id <> t2.id
group by t1.id, t2.id;

I notice your data is symmetric, so (1, 2) is in the data as well as (2, 1). 我注意到您的数据是对称的,因此(1,2)也在(2,1)中。 This means that this logic should work for you. 这意味着该逻辑应该对您有用。 You can add a where clause if you only care about one id. 如果只关心一个ID where则可以添加where子句。

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

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