寻找共同的朋友sql

时间:2016-03-19 01:12:32

标签: sql mutual-friendship

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

表朋友是这样构建的

overflow:hidden

然后表数据看起来像这样

id | user1 | user2 | friend_status

然后让我说我是id为2的用户,然后在该表中我有3个朋友 - 1,3和4.我想要检索的是与用户1共同拥有3个朋友的朋友 - 2, 3和4并从表用户检索2个共同的朋友3和4的数据

3 个答案:

答案 0 :(得分:1)

以下是使用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

答案 1 :(得分:0)

你需要这样的东西吗?

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

答案 2 :(得分:0)

您可以使用UNION来吸引用户朋友:

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

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

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