【问题标题】:Mysql query for search possible FriendsMysql查询搜索可能的朋友
【发布时间】:2014-06-10 15:07:59
【问题描述】:

我有一个朋友表来跟踪我的数据库中的关系 用户之间的连接是双向的。 我正在开发一个“可能的朋友”功能,我需要显示所有不是我朋友的朋友的朋友,并按照从所有共同朋友的降序排列他们

结构表“朋友”:

 user_id    |    friend_id    
    1               2               
    2               1                
    1               3               
    3               1               
    3               4               
    4               3               
    2               6   
    6               2
    3               6
    6               3 

例如,user_id = 1 的可能朋友,这是 6 和 4。

我试图得到这样的东西:

 user_id    |    Possible id    |    id common friends      |    Total common friends    
                 (friend_id)
    1               6                       2                           2
    1               6                       3                           2
    1               4                       3                           1

我该如何做这样的查询?

谢谢你

【问题讨论】:

  • "可能的朋友" = "我朋友的朋友,但不是我的朋友"。你需要分而治之。 1. 拉出“我的朋友”列表(A 组) 2. 拉出 [A 组] 的朋友列表(结果 B 组) 3. 从(B 组)中减去你已经成为朋友的人——即 [Set A](C 组结果) 3. 拉[C 组] 的好友列表(D 组结果) 4. 计算[D 组] 和[A 组] 之间的匹配次数 5. 按此计数排序。你被困在哪里了?

标签: mysql sql


【解决方案1】:

试试这个:

SELECT f1.user_id, 
       f2.friend_id as "Possible id (friend_id)", 
       f1.friend_id as "id common friends",
       f3.total as "Total common friends"
FROM friends f1
INNER JOIN friends f2 on f1.friend_id = f2.user_id and f1.user_id <> f2.friend_id
INNER JOIN (
    SELECT fa.user_id, 
           fb.friend_id, 
           count(fb.friend_id) as total 
    FROM friends fa
    INNER JOIN friends fb on fa.friend_id = fb.user_id and fa.user_id <> fb.friend_id
    GROUP BY fa.user_id, fb.friend_id
) f3 on f3.user_id = f1.user_id and f3.friend_id = f2.friend_id

【讨论】:

  • 我无语了!非常感谢!你帮了我很多=)
猜你喜欢
  • 1970-01-01
  • 2018-07-16
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
相关资源
最近更新 更多