2014-10-06 89 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