相关的子查询朋友

时间:2014-10-06 13:42:19

标签: mysql sql

查询:

select friends_of_first.friend
from (
    select id2 as friend from friend_relastionship where id1 = '4'
    union 
    select id1 as friend from friend_relastionship where id2 = '4'
    ) friends_of_first
join (
    select id2 as friend from friend_relastionship where id1 = '7'
    union 
    select id1 as friend from friend_relastionship where id2 = '7'
    ) friends_of_second
on friends_of_first.friend = friends_of_second.friend;

此查询查找用户4和7之间的共同朋友。

我想用这个作为查找表friend_relastionship中所有共同朋友对的基础,以便我可以选择与最多共同朋友的顶对。我的理解是,我可以在每个与相关子查询配对的情况下运行它,但我不确定如何。

该表的设计方式是id1< id2如果1和7之间存在友谊,那么它被列为1,7而不是7,1。所以友谊会出现一次。

这是一个sqlfiddle:http://sqlfiddle.com/#!2/48eb0/1

在这个sqlfiddle中,它应该显示

 USER1      USER2      COUNT
     3          4          3
     6          7          2
     4         45          2
     2          7          2
     2          6          2
     1          2          2
     1         45          2
     0          2          2

...

表示3和4应该是朋友,因为他们有3个共同的朋友。

2 个答案:

答案 0 :(得分:0)

您尚未显示表结构,因此您必须使用实际列名替换我的列名,但这应该有效:

Select fof1.connection, fof1.friend, fof2.friend from friend_relationship fof1 join friend_relationship fof2 on fof1.connection = fof2.connection where fof1.friend < fof2.friend

然后,您可以对每个连接进行统计,以查看谁拥有最多行。

答案 1 :(得分:0)

这是使用SQL Fiddle中的数据的另一个镜头:

select a.friend1 as ID1, b.friend1 as ID2, count(distinct a.friend2) as connections from ((select id1 as friend1, id2 as friend2 from friend_relastionship) UNION (select id2 as friend1, id1 as friend2 from friend_relastionship))a join ((select id1 as friend1, id2 as friend2 from friend_relastionship) UNION (select id2 as friend1, id1 as friend2 from friend_relastionship))b on a.friend2 = b.friend2 where a.friend1 < b.friend1 group by ID1, ID2 having connections > 1 order by connections desc

您应该考虑通过在下面添加UNION语句作为视图来查看此数据的存储方式或使其更具查询性。