六度分割理论:有一个数学领域的猜想,名为Six Degrees of Separation,中文翻译包括以下几种: 六度分割理论或小世界理论等。 理论指出:你和任何一个陌生人之间所间隔的人不会超过六个,也就是说,最多通过六个人你就能够认识任何一个陌生人。这就是六度分割理论,也叫小世界理论。

比如:A跟B是好友,AB之间的度就是1,B的好友C,也就是A的好友的好友,那AC之间的度就是2。
好友表:(以双向好友表为例)
user_id friend_id
1 2
1 3
2 1
2 3
3 1
3 2
3 4

如果我的id是1 那么我的好友就是2,3 也就是

select friend_id from xxx where user_id=1

这句是查看我的直接好友,也就是一度好友。那么查看二度好友呢?就在循环遍历一遍,也就是查找我的好友的好友
而好友关系是这样 A->B->C C是A的二度好友

select friend_id from xxx where user_id in (select friend_id from xxx where user_id=1)

这是id为1的二度好友,可是如果A->C,那个C与A认识,ABC互相认识,C既可以是A的一度好友也可以是A的二度好友,这时就看要求了,如果要是只查二度好友,就可以用上面的句子,如果要是想看不认识的二度好友,就像人人网的好友推荐那样,还要在上面的结果中把A的好友去除,也就是

select friend_id from xxx where user_id in (select friend_id from xxx where user_id=1) and friend_id not in(select friend_id from xxx where user_id=1)

括号内为一度好友查询,这样就是不认识的二度好友了。

二度好友就是在一度好友的情况下,在遍历一遍,如果每个人的好友有n个,那么你的二度好友就是n*n个。

根据上述sql出的结果是二度好友数,可是还有情况是好友是自己,也就是循环一圈回来了- -!,因为是双向好友表嘛,需要在结果中把自己的id去掉

select friend_id from xxx where user_id in (select friend_id from xxx where user_id=1) and friend_id not in(select friend_id from xxx where user_id=1) and friend_id <> 1

括号内为一度好友查询
可以根据group by 分下组 就知道了自己不认识的人 和自己有多少个共同好友 也就是人人的好友推荐了

查询两人的共同好友:
如果查询用户1,2之间的共同好友 也就是像人人那样查看
1->X->2这种关系 由于好友表只是一度关系 查询两度遍历下就行了
Java代码
select friend_id from xxx where user_id=1 and friend_id in(select friend_id from xxx where user_id=2)

这就是查1,2的共同好友了.