【问题标题】:Finding mutual friend sql寻找共同好友sql
【发布时间】:2016-03-19 01:12:31
【问题描述】:

实际上我有 2 个表,朋友表和用户表 我试图实现的是通过检查另一个用户的朋友来检索我的共同朋友,并从用户表中获取这些共同朋友的数据

桌友是这样搭建的

id | user1 | user2 | friend_status

那么表格数据是这样的

1 | 1 | 2 | 1
2 | 1 | 3 | 1
3 | 2 | 3 | 1
4 | 1 | 4 | 1
5 | 2 | 4 | 1

然后假设我是 id 为 2 的用户,那么在该表中我有 3 个朋友 - 1、3 和 4。我要检索的是用户 1 的普通朋友也有 3 个朋友 - 2, 3 和 4 并从表 users 中检索 2 个共同的共同朋友 3 和 4 的数据

【问题讨论】:

  • 我们在谈论MySql吗?

标签: sql mutual-friendship


【解决方案1】:

您可以使用UNION 来获取用户朋友:

SELECT User2 UserId FROM friends WHERE User1 = 1
  UNION 
SELECT User1 UserId FROM friends WHERE User2 = 1

然后,在UserId 上为两个不同的用户加入其中的两个UNION,您可以获得共同的朋友:

SELECT UserAFriends.UserId FROM
(
  SELECT User2 UserId FROM friends WHERE User1 = 1
    UNION 
  SELECT User1 UserId FROM friends WHERE User2 = 1
) AS UserAFriends
JOIN  
(
  SELECT User2 UserId FROM friends WHERE User1 = 2
    UNION 
  SELECT User1 UserId FROM friends WHERE User2 = 2
) AS UserBFriends 
ON  UserAFriends.UserId = UserBFriends.UserId

【讨论】:

  • 感谢 xpy,但我在哪里可以从该查询中的用户表中获取共同朋友的信息?
  • 此查询返回共同好友的 id,您可以通过将此查询的结果与您的 users 表连接来获取信息。
【解决方案2】:

这是一种使用union all 组合用户1 和用户2 的所有朋友并使用count(distinct src) > 1 仅选择与这两个用户都是朋友的方法。

select friend from (
    select 2 src, user1 friend from friends where user2 = 2
    union all select 2, user2 from friends where user1 = 2
    union all select 1, user1 from friends where user2 = 1
    union all select 1, user2 from friends where user1 = 1
) t group by friend
having count(distinct src) > 1

【讨论】:

    【解决方案3】:

    你需要这样的东西吗?

    create table #table (id int, user1 int , user2 int, friend_status int)
    
    insert into #table values
    
    (1 , 1 , 2 , 1),
    (2 , 1 , 3 , 1),
    (3 , 2 , 3 , 1),
    (4 , 1 , 4 , 1),
    (5 , 2 , 4 , 1),
    (6 , 2 , 1 , 1),
    (7,  3 , 7 , 1)
    
    select *from #table
    
    select t1.user1, t1.user2 as friend
    from #table t1
    inner join
    #table  t2
    on (t1.user2 = t2.user2
    and t1.user1 <> t2.user1)
    where t1.user1<>2
    order by t1.user1
    

    【讨论】:

    • 他想要用户1和用户2的共同好友
    • 它只获取普通朋友
    • 如果我猜对了,它会获取 id 为 2 的用户和所有其他用户的所有共同朋友。
    • 是的..我认为 Mireille28 需要所有拥有朋友 1 、 3 、 4 的用户(用户 2 的朋友)。如果用户 1 需要它,那么添加 t1.user1=1 行就足够了
    • 他需要1和2的共同朋友。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    相关资源
    最近更新 更多