问题
示例表
+-------------+----------------------+--------+
| 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.
借鉴Managing Hierarchical Data in 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
答案 0 :(得分:2)
您可以使用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