简体   繁体   English

共同的朋友-MySQL

[英]Mutual Friends - MySQL

I am trying to develop a function which shows me friends of friends, and how many mutual friends I have with those users. 我正在尝试开发一个功能,向我显示朋友的朋友,以及与这些用户有多少个共同的朋友。 So far, I have been able to do the functions separately but not together. 到目前为止,我已经能够分别执行这些功能,但不能一起执行。

Here is the main view I am using called userfriends . 这是我使用的主要视图,称为userfriends Where user1 is the first user and user2 is the friend. 其中user1是第一个用户,而user2是朋友。

在此处输入图片说明

This is the function I have developed to see mutual friends between two users 这是我开发的功能,用于查看两个用户之间的共同朋友

SELECT id FROM users
WHERE id IN (
    SELECT user2 FROM userfriends WHERE user1 = me
) AND id IN (
    SELECT user2 FROM userfriends WHERE user1 = second
)

Users is a main table which can link the user id found in the userfriends table to information about the user. Users是一个主表,可以将在userfriends表中找到的用户ID链接到有关该用户的信息。 Me and second are variables in the stored procedure which emulate the search for first and second users. Me和second是存储过程中的变量,它们模拟对第一和第二用户的搜索。 This function works to plan. 此功能可以计划。

The second function I have is to see all the users who are friends with my friends, but not with me. 我的第二个功能是查看与我的朋友成为朋友的所有用户,而不是与我成为朋友。

SELECT user2 AS id
FROM userfriends
    WHERE user1 IN (
        #Selects my friends
        SELECT user2 FROM userfriends
        WHERE user1 = me
    ) 
    AND user2 <> me #Makes sure is not me
    AND user2 NOT IN ( #Makes sure not already friend
        SELECT user2 FROM userfriends
        WHERE user1 = me
    )

Again, all working to plan and me represents the user id. 同样,所有要计划的工作和我都代表用户ID。 This will return a list of all my friends friends. 这将返回我所有朋友的列表。

What I want to be able to get instead of a list of mutual users, or a list of my friends friends is: 我希望获得的不是共有用户列表,也不是我的朋友朋友列表:

A table which has my friends friend user ID and how many mutual friends me and that user shares. 该表包含我的朋友朋友用户ID以及我与该用户共享的共同朋友数量。 Etc: user: 1, friends_in_common: 103. If I'm not clear enough please ask and I will try and make it clearer. 等等:用户:1,friends_in_common:103。如果我不清楚,请询问,我将尝试使其更清楚。 The two functions do it by themselves, but I'm just not sure how to merge it together. 这两个功能是自己完成的,但是我不确定如何将它们合并在一起。

-- use a self-join of userfriend*userfriend
-- to find all the friends that moi&toi have in common
-- , and count them.
-- (optionally) suppress the rows for (toi<=moi)
-- , because there are basically the same as the corresponding rows with
-- (toi>moi)
-- -----------------------------------
SELECT DISTINCT 
   uf1.user1 AS moi
   , uf2.user1 AS toi
   , COUNT(*) AS cnt
   FROM userfriend uf1
   JOIN userfriend uf2 ON uf1.user2 = uf2.user2
   WHERE uf1.user1 < uf2.user1 -- Tie breaker, symmetry remover
   GROUP BY uf1.user1, uf2.user1
   ; 

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

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