pl / sql分层数据安排

时间:2014-06-30 13:09:19

标签: sql oracle11g hierarchical

表tMain:

+----+-------+---------+
| ID | name  | id_ref  |
+----+-------+---------+
| 1  | amine |      4  |
| .. |       |         |
+----+-------+---------+

表格tTree:

+----+--------+-----------+
| ID |  name  | id_parent |
+----+--------+-----------+
|  1 | root   | null      |
|  2 | child1 | 1         |
|  3 | child2 | 2         |
|  4 | child3 | 3         |
+----+--------+-----------+

所以我需要表格,我想“连接”。表“tMain”包含一些数据和引用tTree表的外键(对最低子项的引用)。我想要的是使用一个查询来获取来自tMain的所有数据以及来自tTree的汇编路径。它看起来像这样:

+----+-------+--------+---------------------------+
| ID | name  | id_ref |           Path            |
+----+-------+--------+---------------------------+
| 1  | amine |      4 | root/child1/child2/child3 |
| .. |       |        |                           |
+----+-------+--------+---------------------------+

1 个答案:

答案 0 :(得分:2)

WITH tree$ AS (
    SELECT T.id, ltrim(sys_connect_by_path(name, '/'), '/') AS path
    FROM tTree T
    START WITH id_parent IS NULL
    CONNECT BY PRIOR ID = id_parent
)
SELECT T.id, M.name, M.id_ref, T.path
FROM tMain M
    JOIN tree$ T ON T.id = M.id_ref
;