简体   繁体   English

如何编写这个 PL/SQL 查询?

[英]How do I write this PL/SQL query?

I have a table with 2 columns: Person (1), his/her friends (2).我有一个有 2 列的表:人 (1),他/她的朋友 (2)。

I need a query to select all of Tom's friends, friends of his friends, friends of their friend and so on... Maybe some SQL or PL/SQL can do this?我需要查询 select 所有汤姆的朋友,他朋友的朋友,他们朋友的朋友等等......也许一些 SQL 或 PL/SQL 可以做到这一点?

For example for Tom this query should return: Sara, Anna, Alex, Lisa.例如,对于 Tom,此查询应返回:Sara、Anna、Alex、Lisa。

Person His/Her friends他/她的朋友
Tom汤姆 Sara萨拉
Tom汤姆 Anna安娜
Anna安娜 Tom汤姆
Anna安娜 Alex亚历克斯
Alex亚历克斯 Anna安娜
Alex亚历克斯 Lisa丽莎

You can use a hierarchical query to continue from a friend to a friend or a friend and so on:您可以使用分层查询从朋友继续到朋友或朋友等等:

SELECT     DISTINCT friend_name
FROM       friends
WHERE      friend_name != 'Tom'
START WITH name = 'Tom'
CONNECT BY NOCYCLE PRIOR friend_name = name

EDIT:编辑:
To address the question in the comment about the nocycle option: Without any restriction, a hierarchical query could in theory recurse forever.为了解决关于nocycle选项的评论中的问题:没有任何限制,分层查询理论上可以永远递归。 Eg, with this data, Tome has a friend called Anna.例如,有了这些数据,Tome 有一个叫 Anna 的朋友。 Anna, in turn, has a friend called Tom, and without any restriction, the query could go on indefinitely between these two friends, which will cause it to fail with an "ORA-01436: CONNECT BY loop in user data" error.反过来,安娜有一个叫汤姆的朋友,并且没有任何限制,查询可以在这两个朋友之间无限期地打开 go,这将导致它失败并出现“ORA-01436:用户数据中的 CONNECT BY 循环”错误。 The NOCYCLE option prevents this repetition and allows the query to complete without "going back" to values it's already visited. NOCYCLE选项可防止这种重复,并允许查询完成而无需“返回”到已访问过的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM