所以有一个friendship_request表:
+--------+----------+
| sender | receiver |
+--------+----------+
| 1 | 2 |
| 2 | 1 |
+--------+----------+
如果两个用户都互相发送了请求,则两个用户就是朋友。
我正在使用PHP的array_intersect和包含每个用户的所有朋友的数组来确定它们是否通过朋友的朋友连接。
即。
1 <--> 2 <--> 3
如果两个用户的朋友有朋友,彼此是朋友,那么最有效的方法是什么。 即
+--------+----------+
| sender | receiver |
+--------+----------+
| 1 | 2 |
| 2 | 1 |
| 2 | 3 |
| 3 | 2 |
| 3 | 4 |
| 4 | 3 |
+--------+----------+
1 <--> 2 <--> 3 <--> 4
用户1应该知道他与用户4的关系。
PS:PHP /伪代码或MySQL
没关系编辑:我不想创建另一个表或视图。我想使用上述资源获得最佳解决方案。
答案 0 :(得分:0)
我会创建一个图形结构。邻接列表表示可以很好地工作。然后你可以运行深度优先搜索。
答案 1 :(得分:0)
首先创建检测友谊的视图:
CREATE VIEW friendship (friend1, friend2)
AS SELECT p1.id, p2.id from person as p1, person as p2
WHERE
(SELECT count(*) from friendship_request as fr1 WHERE
fr1.sender = p1.id AND fr1.receiver = p2.id) > 0
AND
(SELECT count(*) from friendship_request as fr2 WHERE
fr2.receiver = p1.id AND fr1.sender = p2.id) > 0
现在查询第一级连接就像
一样简单SELECT p1.name, p1st.name, p2.name
FROM person as p1, person as p2, person as p1st,
friendship as fs1, friendship as fs2
WHERE p1.id = fs1.friend1
AND p2.id = fs2.friend1
AND fs1.frind2 = fs2.frind2
AND fs2.frind2 = p1st.id
用于第二级连接:
SELECT DISTINCT p1.name, p2nd1.name, p2nd2.name, p2.name
FROM person as p1, person as p2, person as p2nd1, person as p2nd2,
friendship as fs1, friendship as fs2, friendship as fs2nd
WHERE p1.id = fs1.friend1
AND p2.id = fs2.friend1
AND fs1.frind2 = fs2nd.frind2
AND fs2.frind2 = fs2nd.frinend2
AND p2nd1.id = fs1.frind2
AND p2nd2.id = fs2.frind2
等等。
没有测试,但在任何正常的RDBMS应该工作: - )