简体   繁体   English

SQL查询查找给定的人,朋友对表的共同朋友数

[英]SQL Query to find number of mutual friends given a table of person, friend pair

I have searched for other questions and I was able to solve part of what I wanted but I couldn't get any further from that. 我已经搜索了其他问题,并且能够解决我想要的部分问题,但对此我无能为力了。

I have a table with two columns(user, friend) in Friends table. 我在朋友表中有一个带有两列(用户,朋友)的表。 Each user and his/her friend is specified in the table as bellow. 每个用户及其朋友在表中都指定为波纹管。

User | Friend
1        2
1        6
2        1
2        3
2        6

Note: For every (User, friend) pair there is a row (Friend, User) Eg: 1,2 has 2,1 because User 2 has friend 1 注意:对于每对(用户,朋友),都有一行(朋友,用户)例如:1,2有2,1,因为用户2有朋友1

So far, I have arrived at the below query which gives the count of mutual friends for the pair we specify: 到目前为止,我到达了以下查询,该查询提供了我们指定的对的共同朋友数:

select DISTINCT f1.user1 'User', f2.user1 'Friend', COUNT(DISTINCT     f1.user2) 'Mutual friends'
from Friends p
inner join Friends f1 on f1.user2 = p.user1
inner join Friends f2 on f2.user2 = p.user1
where f1.user1 = 2 and f2.user1 = 3 and f1.user2 = f2.user2
group by f1.user1, f2.user1;

The output that I have now: 我现在的输出:

User    |Friend |Mutual Friends
1            2      1

I want to find the count of mutual friends of each of pairs throughout the table: 我想查找整个表格中每对的共同朋友的数量:

User |  Friend |  Mutual Friends
1        2        1
1        6        0
2        1        1
2        3        0
2        6        0

How do I find the number of mutual friends for all user,friend pairs? 如何找到所有用户,朋友对的共同朋友数?

You can use a self-join: 您可以使用自联接:

select f1.user as user1, f2.user as user2, count(*) as num_in_common
from friends f1 join
     friends f2
     on f1.friend = f2.friend 
group by f1.user, f2.user;

You can add a where clause if you want this information for a particular pair of users. 如果需要特定用户对的信息,则可以添加where子句。

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

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