在邻接列表中查找后代深度

发布于 2024-09-28 12:08:06 字数 1181 浏览 3 评论 0原文

问题

示例表

+-------------+----------------------+--------+
| category_id | name                 | parent |
+-------------+----------------------+--------+
|           1 | ELECTRONICS          |   NULL |
|           2 | TELEVISIONS          |      1 |
|           3 | TUBE                 |      2 |
|           4 | LCD                  |      2 |
|           5 | PLASMA               |      2 |
|           6 | PORTABLE ELECTRONICS |      1 |
|           7 | MP3 PLAYERS          |      6 |
|           8 | FLASH                |      7 |
|           9 | CD PLAYERS           |      6 |
|          10 | 2 WAY RADIOS         |      6 |
+-------------+----------------------+--------+

鉴于上面的示例表,我认为在 Oracle 中我应该能够沿着“SELECT ... CONNECT BY”的行编写 SQL 来查找给定 id 的级别。例如,“MP3 播放器”的 LEVEL 为 3。

示例借自 管理层次结构MySQL中的数据

解决方案

SELECT MAX(level) "LEVEL"
FROM TEST_TABLE
START WITH category_id = 7 -- MP3 Players category_id
CONNECT BY category_id = PRIOR parent
ORDER BY LEVEL DESC

Question

Example Table

+-------------+----------------------+--------+
| category_id | name                 | parent |
+-------------+----------------------+--------+
|           1 | ELECTRONICS          |   NULL |
|           2 | TELEVISIONS          |      1 |
|           3 | TUBE                 |      2 |
|           4 | LCD                  |      2 |
|           5 | PLASMA               |      2 |
|           6 | PORTABLE ELECTRONICS |      1 |
|           7 | MP3 PLAYERS          |      6 |
|           8 | FLASH                |      7 |
|           9 | CD PLAYERS           |      6 |
|          10 | 2 WAY RADIOS         |      6 |
+-------------+----------------------+--------+

Given the example table above, I'm thinking in Oracle I should be able to write SQL along the lines of "SELECT ... CONNECT BY" to find the level of a given id. For example, "MP3 Players" has a LEVEL of 3.

Example borrowed from Managing Hierarchical Data in MySQL

Solution

SELECT MAX(level) "LEVEL"
FROM TEST_TABLE
START WITH category_id = 7 -- MP3 Players category_id
CONNECT BY category_id = PRIOR parent
ORDER BY LEVEL DESC

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

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

发布评论

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

评论(1

2024-10-05 12:08:06

您可以使用level伪列来获取当前行的“深度”。考虑以下陈述:

SELECT category_id, name, level,
 PRIOR name as parent_category
FROM test_table
START WITH parent is null
CONNECT BY PRIOR category_id = parent

You can use level pseudocolumn to get the "depth" of the current row. Consider the following statement:

SELECT category_id, name, level,
 PRIOR name as parent_category
FROM test_table
START WITH parent is null
CONNECT BY PRIOR category_id = parent
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文