2014-10-06 88 views
-1

查询:相关子查询的朋友

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周共同的朋友。

回答

0

下面是使用在SQL小提琴数据再出手:

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语句视图。

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

然后,您可以只是做一个计数每个连接上查看谁拥有最多的行。

+0

什么是连接? – ParoX 2014-10-06 15:18:34

+0

连接是id1和id2共有的朋友。 – JLampon 2014-10-06 17:08:47

+0

我看不到它来自哪里。我知道连接是我postesd查询的结果,但我如何让这个查询在每个组合上运行? – ParoX 2014-10-06 17:41:22