如何获得“链接” SQL 查询中的项目

发布于 2024-10-01 11:40:23 字数 478 浏览 0 评论 0原文

我在 SQL 数据库表中创建了一个“自下而上”的树,其中每个元素都有一个列用于引用其父元素。现在我试图找出是否有一个简单的查询可以获取孩子的所有父母。

例如:

                          [ Parent #1 ]
                                |
               [Parent #2]             [Parent #3]
                    |                       |
         [Child # 1] [Child #2]   [Child #3] [Child #4]

我将 Child #1 作为“ID”。每个条目都有对其父项的引用,并且最顶层父项的父项 id 为空。因此,我不是在代码中递归并获取每个父级,而是希望有一个查询可以通过仅提供子级 1 id 来获取父级 1 id、父级 2 id 和子级 1 id。

I have created a 'bottom-up' tree in my SQL database tables where each element has a column for a reference to its parent. Now I am trying to find out if there is an easy query to get all the parents of a child.

For example:

                          [ Parent #1 ]
                                |
               [Parent #2]             [Parent #3]
                    |                       |
         [Child # 1] [Child #2]   [Child #3] [Child #4]

I am giving Child #1 as the 'ID'. Each entry has reference to it's parent, and the topmost parent is null for parent id. So instead of in my code recursing and getting each parent, I was hoping there was a query I could do that would get Parent 1 id, parent 2 id, and child 1 id by just providing child 1 id.

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

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

发布评论

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

评论(3

心凉 2024-10-08 11:40:23

您希望使用分层查询,并使用 START WITH 和 CONNECT BY 子句。请参阅此链接

You'd want to use a hierarchical query, using the START WITH and CONNECT BY clauses. See this link.

西瑶 2024-10-08 11:40:23

这只是一个层次检索
我猜到了一个查询,所以欢迎改进。

选择node_id
来自树
哪里 child_id="child_1"
从 id="child_1" 开始
按先前的方式连接parent_id=child_id;

It's just a Hierarchical Retrieval
I guessed a query , so improvements are welcome.

SELECT node_id
FROM tree
WHERE child_id="child_1"
START WITH id="child_1"
CONNECT BY PRIOR parent_id=child_id;

鸢与 2024-10-08 11:40:23

您还可以使用嵌套集邻接模型。两者都具有可与任何 SQL 数据库配合使用的优势。邻接模型仅适用于少量有限的嵌套深度,而嵌套集可以嵌套无限的深度。

You also can use a nested set or adjacency model. Both have the advantage to work with any SQL database. The adjacency model works only good with a small limited number of nesting depth, while a nested set can be nested with an unlimited depth.

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