简体   繁体   中英

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

user_id 2 - 1,3

user_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. Similar to facebook 'all friends' feature that will show the mutual friends.
The input will be '1' the output will be

user_id 2 return 1 mutual friends

user_id 3 return 1 mutual friends

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 .

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.

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