寻找三度网络的更有效方法

More efficient way to find 3rd degree network

我正在尝试开发一个功能来显示用户的三度网络(朋友、朋友的朋友、朋友的朋友的朋友)。类似于 Linkedin 的做法。

我有一个解决方案,但它似乎效率低下并且对数据库进行了很多查询。有没有比下面的伪代码更好的已知方法来查找用户的 3 度关系?我是 php(和编程)新手,所以如果我错过了一些明显的事情,请提前致歉。谢谢。

Query table to find user’s 1st connections.
    Push to Array1()

For (x = 0; x < count (Array1); x++){
    Query table to find Array1[x]’ s 1st connections and push to Array2();
}

For (y =0; y < count(Array2); y++){
    Query table to find Array2[y]’s 1st connections and push to Array3();
}

Array4 = array_unique(Array3);

数据库中的2个表有这样的结构:

members           
id, username, password, id

connections        
connectionId, userID, friendID, confirmed

您可以使用 3 个带有 'in' 子句的子查询来查询 Array4

select friendID from connections where userID  in (
select friendID from connections where userID  in (
select friendID from connections where userID in (
select friendID from connections where userID = 1)))

并且不要忘记创建索引