简体   繁体   English

使用 MySql 检查我朋友的共同好友

[英]Check Mutual Friends from my friend using MySql

For the first table:对于第一个表:

user_id | name
1         Me
2         Jeremy
3         Bob
4         Kelvin

For the second table:对于第二个表:

user_id | friend_id
1         2
1         3
2         1
2         3
3         1
3         2

Therefore, the friend relationship will like this:所以朋友关系会是这样的:

user_id 1 - 2,3用户 ID 1 - 2,3

user_id 2 - 1,3用户 ID 2 - 1,3

user_id 3 - 1,2用户 ID 3 - 1,2

If let say I'm user_id 1 which is 'Me', then I need to display all my friends and show the mutual friends.如果说我是 user_id 1,即“我”,那么我需要显示我所有的朋友并显示共同的朋友。 Similar to facebook 'all friends' feature that will show the mutual friends.类似于 facebook 的“所有朋友”功能,将显示共同的朋友。
The input will be '1' the output will be输入将为“1”,输出将为

user_id 2 return 1 mutual friends user_id 2 返回 1 个共同好友

user_id 3 return 1 mutual friends user_id 3 返回 1 个共同好友

I've been researching a long time, but have not tried out workable code.我已经研究了很长时间,但还没有尝试过可行的代码。

Use self joins and aggregation:使用自连接和聚合:

SELECT t2.user_id, SUM(t2.friend_id <> t1.user_id) mutual_friends
FROM tablename t1
INNER JOIN tablename t2 ON t2.user_id = t1.friend_id 
LEFT JOIN tablename t3 ON t3.user_id = t1.user_id AND t3.friend_id = t2.friend_id
WHERE t1.user_id = 1
GROUP BY t2.user_id;

See the demo .请参阅演示

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

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