选择查询以将朋友返回到第五级
我正在尝试从图形数据库书籍中实现社交网络问题,但在SQL中(使用PostgreSQL)。我有这两张桌子,可以定义一个人及其与他人的友谊。
CREATE TABLE IF NOT EXISTS Person(
ID INTEGER PRIMARY KEY,
Person VARCHAR(200)
);
CREATE TABLE IF NOT EXISTS PersonFriend(
PersonID INTEGER,
FriendID INTEGER,
PRIMARY KEY (PersonID, FriendID)
);
我正在寻找的是一个查询,它将归还所有人的朋友,朋友的朋友,朋友的朋友等人,直到一个人的第五级。
我已经连接了我在neo4j中制作的图形示例,该示例应该有助于可视化。我使用Cypher轻松解决了它,但是我在SQL中遇到了一些麻烦。使用爱丽丝作为参考,我的疑问应该将奥利维亚,扎克,鲍勃,玛丽,凯特琳,紫罗兰和Zerus返回,因为他们是她(直接和间接)的朋友,直到第五级。
该书包括此代码段,但仅升至第二级(并且不返回第一个)。
SELECT p1.Person AS PERSON, p2.Person AS FRIEND_OF_FRIEND
FROM PersonFriend pf1 JOIN Person p1
ON pf1.PersonID = p1.ID
JOIN PersonFriend pf2
ON pf2.PersonID = pf1.FriendID
JOIN Person p2
ON pf2.FriendID = p2.ID
WHERE p1.Person = 'Alice' AND pf2.FriendID <> p1.ID
我非常感谢任何解决此问题的建议。
I am trying to implement the social network problem from the Graph Databases book, but in SQL (using PostgreSQL). I have these 2 tables, that will define a person and their friendship with someone else.
CREATE TABLE IF NOT EXISTS Person(
ID INTEGER PRIMARY KEY,
Person VARCHAR(200)
);
CREATE TABLE IF NOT EXISTS PersonFriend(
PersonID INTEGER,
FriendID INTEGER,
PRIMARY KEY (PersonID, FriendID)
);
What I am looking for is a query that will return all the friends, friends of friends, friends of friends of friends, etc, up to the 5th level, of a person.
I've attached a graph example that I made in Neo4j that should help the visualization. I solved it easily using Cypher, but I'm having some trouble to do the equivalent in SQL. Using Alice as reference, my query should return Olivia, Zach, Bob, Mary, Caitlyn, Violet and Zerus, as they're her (direct and indirect) friends up to the 5th level.
The book includes this snippet of code, but it only goes up to the 2nd level (and does not return the first one).
SELECT p1.Person AS PERSON, p2.Person AS FRIEND_OF_FRIEND
FROM PersonFriend pf1 JOIN Person p1
ON pf1.PersonID = p1.ID
JOIN PersonFriend pf2
ON pf2.PersonID = pf1.FriendID
JOIN Person p2
ON pf2.FriendID = p2.ID
WHERE p1.Person = 'Alice' AND pf2.FriendID <> p1.ID
I would very much appreciate any suggestions to solve this problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
递归查询是处理此问题的最简单方法:
SideNote,您应该使用
text
类型而不是varchar(200)
。Recursive queries are the easiest way to handle this:
Sidenote, you should be using the
text
type and notVARCHAR(200)
.