SQL 层次结构问题

发布于 2024-08-03 05:14:15 字数 248 浏览 14 评论 0原文

我有一个基本的实体树结构。树的深度最多为 5 个节点,但宽度可能为 N 个节点。我已在表中映射了这种关系,如下所示:

myID | myDescription | myParentID

我从一个已知对象开始,这可以转换为具有起始“myID”。现在我想获取所有的子节点。有没有一种方法可以在一个语句中获取所有子节点?这需要包括我孩子的孩子,并继续下去。我正在使用 Oracle SQL。

谢谢, 杰伊

I have a basic tree structure of entities. The tree can be a maximum of 5 nodes deep, but may be N nodes wide. I have mapped this relationship in table similar to what is shown below:

myID | myDescription | myParentID

I am starting out with a known object, which could translate to having a starting "myID". Now I want to get all the child nodes. Is there a way of getting all the child nodes in one statement? This needs to include the children of my children, and going on down the tree. I am using Oracle SQL.

Thanks,
Jay

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

江湖正好 2024-08-10 05:14:15
SELECT  *
FROM    mytable
START WITH
        myid = :id
CONNECT BY
        myparentid = PRIOR myid
SELECT  *
FROM    mytable
START WITH
        myid = :id
CONNECT BY
        myparentid = PRIOR myid
七分※倦醒 2024-08-10 05:14:15

如果您想在单个查询中检索所有节点,我建议使用另一种方法来建模层次结构。一种非常好的、常见的实现是嵌套集模型。本文概述了如何在 MySQL 中实现这一点,但它可以轻松移植到 Oracle。

I would suggest using another way to model your hierarchy if you want to retrieve all nodes in a single query. One very good, and common, implementation is the nested set model. The article outlines how this is implemented in MySQL, but it can easily be ported to Oracle.

可可 2024-08-10 05:14:15

实现此目的的一种可能的巧妙方法是添加另一个包含记录“路径”的字段。假设最上面的记录是 ID=1。它有一个 ID = 5 的子级,并且它还有一个 ID = 20 的子级,那么最后一条记录将具有路径
/1/5/20
因此,如果您想要顶部节点的所有子节点,您可以这样做

select * from MyTable where Path like '/1/%'

(抱歉,sql server语法,我不是oracle开发人员 - 但这个概念仍然适用)

要获取中间节点的子节点,

select * from MyTable where Path like '/1/5/%'

该解决方案的巧妙之处在于您可以将索引应用于“路径”字段,因此该语句将仅使用单个索引扫描来执行,从而非常高效。

A possible neat way to implement this is to add another field that contains the "path" to the record. Say the top record is ID=1. It has a child with ID=5, and it again has a child with ID=20, then the last record would have the path
/1/5/20
So if you want all child nodes of you top node you do

select * from MyTable where Path like '/1/%'

(sorry, sql server syntax, I'm not an oracle developer - but the concept would still apply)

To get children of the middle node

select * from MyTable where Path like '/1/5/%'

The neat thing about that solution is that you can apply indexes to the "path" field, so the statement will execute using only a single index scan making it very efficient.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文