【问题标题】:Mutual Friends - MySQL共同的朋友 - MySQL
【发布时间】:2012-12-24 09:52:02
【问题描述】:

我正在尝试开发一种功能,该功能可以显示朋友的朋友,以及我与这些用户有多少共同朋友。到目前为止,我已经能够单独执行这些功能,但不能一起执行。

这是我使用的名为 userfriends 的主视图。其中 user1 是第一个用户,user2 是朋友。

这是我开发的用于查看两个用户之间的共同朋友的功能

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 是一个主表,它可以将在 userfriends 表中找到的用户 id 链接到有关用户的信息。 Me 和 second 是存储过程中的变量,用于模拟搜索第一个和第二个用户。此功能按计划工作。

我的第二个功能是查看所有与我的朋友成为朋友的用户,而不是与我成为朋友的用户。

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
    )

再一次,所有工作都在计划中,我代表用户 ID。这将返回我所有朋友的列表。

我希望能够得到的不是共同用户列表,或者我的朋友朋友列表是:

一个表,其中包含我的朋友朋友用户 ID 以及我和该用户共享的共同朋友的数量。等:用户:1,friends_in_common:103。如果我不够清楚,请询问,我会尝试使其更清楚。这两个函数是自己做的,但我只是不确定如何将它合并在一起。

【问题讨论】:

    标签: mysql database mutual-friendship


    【解决方案1】:
    -- 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
       ; 
    

    【讨论】:

    • 嘿,这似乎在做什么?但是你能解释一下吗?因为我不是 100% 确定它是正确的
    • 你去。 (对我来说,SQL 比我的文字解释更具可读性 ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    相关资源
    最近更新 更多