在邻接列表中查找后代深度
问题
示例表
+-------------+----------------------+--------+
| 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
level
伪列来获取当前行的“深度”。考虑以下陈述:You can use
level
pseudocolumn to get the "depth" of the current row. Consider the following statement: