如何使用SQL获取叶节点的根节点信息

时间:2014-04-30 07:52:58

标签: sql oracle hierarchical-data

假设我有一个具有以下结构的表:

---------------------------------------------------
TREE_GID | NODE_ID | PARENT_NODE_ID | TREE_NAME   |
---------------------------------------------------
1        | 1       |                | A           |
1        | 2       | 1              |             |
1        | 3       | 1              |             |
1        | 4       | 2              |             |
1        | 5       | 4              |             |
1        | 6       |                | B           |
1        | 7       | 6              |             |
2        | 1       |                | C           |
2        | 2       | 1              |             |
---------------------------------------------------

注意:

  • 数据模型是多级树。
  • TREE_GID是树的组。它可以有一棵以上的树。
  • NODE_ID是每个TREE_GID中的唯一编号。
  • TREE_NAME仅在根节点中显示。

我想在每个节点中显示TREE_NAME。 输出应该是:

---------------------------------
TREE_ID | NODE_ID | TREE_NAME   |
---------------------------------
1       | 1       | A           |
1       | 2       | A           |
1       | 3       | A           |
1       | 4       | A           |
1       | 5       | A           |
1       | 6       | B           |
1       | 7       | B           |
2       | 1       | C           |
2       | 2       | C           |
---------------------------------

我怎样才能得到它们?

1 个答案:

答案 0 :(得分:1)

递归公用表表达式将以相当直接的方式执行;

WITH cte(tree_gid, node_id, tree_name) AS (
  SELECT tree_gid, node_id, tree_name FROM mytable WHERE tree_name IS NOT NULL
  UNION ALL
  SELECT m.tree_gid, m.node_id, cte.tree_name
  FROM mytable m 
  JOIN cte ON cte.node_id = m.parent_node_id AND cte.tree_gid = m.tree_gid 
)
SELECT * FROM cte
ORDER BY tree_gid, node_id;

编辑:您也可以使用CONNECT BY作为评论链接描述;

SELECT tree_gid, node_id, CONNECT_BY_ROOT tree_name
  FROM mytable
  START WITH tree_name IS NOT NULL
  CONNECT BY PRIOR node_id = parent_node_id AND PRIOR tree_gid = tree_gid
  ORDER SIBLINGS BY tree_gid, node_id;

An SQLfiddle to test both