7

我有一个格式为层次结构的表

CREATE TABLE tree_hierarchy (
  id        NUMBER (20)
 ,parent_id NUMBER (20)
);


INSERT INTO tree_hierarchy (id, parent_id) VALUES (2, 1);
INSERT INTO tree_hierarchy (id, parent_id) VALUES (4, 2);
INSERT INTO tree_hierarchy (id, parent_id) VALUES (9, 4);

当我运行查询时:-

SELECT id,parent_id,
  CONNECT_BY_ISLEAF leaf,
  LEVEL,
  SYS_CONNECT_BY_PATH(id, '/') Path,
  SYS_CONNECT_BY_PATH(parent_id, '/') Parent_Path
FROM tree_hierarchy
WHERE CONNECT_BY_ISLEAF<>0
  CONNECT BY PRIOR id = PARENT_id
ORDER SIBLINGS BY ID;

我得到的结果是这样的:-

"ID"    "PARENT_ID" "LEAF"  "LEVEL" "PATH"  "PARENT_PATH"

9            4         1       3    "/2/4/9"  "/1/2/4"

9            4         1       2     "/4/9"     "/2/4"

9            4         1       1      "/9"      "/4"

但我需要一个 Oracle Sql 查询,它只给我这个

"ID"    "PARENT_ID" "LEAF"  "LEVEL" "PATH"  "PARENT_PATH"

9            4         1       3    "/2/4/9"  "/1/2/4"

这是一个更简单的示例,我以这种方式拥有超过 1000 条记录。当我运行上述查询时,它会生成许多重复项。任何人都可以给我一个通用查询,它将给出从叶子到根的完整路径而没有重复项。谢谢提前寻求帮助

4

2 回答 2

5

有限层次结构中的根节点必须始终是已知的。根据定义:http ://en.wikipedia.org/wiki/Tree_structure 根节点是没有父节点的节点。要检查给定节点是否为根节点,请获取“parent_id”并在表中检查是否存在具有此 ID 的记录。查询可能如下所示:

SELECT id,parent_id,
  CONNECT_BY_ISLEAF leaf,
  LEVEL,
  SYS_CONNECT_BY_PATH(id, '/') Path,
  SYS_CONNECT_BY_PATH(parent_id, '/') Parent_Path
FROM tree_hierarchy th
WHERE CONNECT_BY_ISLEAF<>0
  CONNECT BY PRIOR id = PARENT_id
START WITH not exists (
      select 1 from tree_hierarchy th1 
      where th1.id = th.parent_id
  )
ORDER SIBLINGS BY ID;
于 2013-07-12T16:52:08.973 回答
0

您应该明确指出 id 来构建路径。现在您的查询正在为所有满足您条件的叶子构建路径。您需要使用“start with”让我们这样尝试:

SELECT id,parent_id,
  CONNECT_BY_ISLEAF leaf,
  LEVEL,
  SYS_CONNECT_BY_PATH(id, '/') Path,
  SYS_CONNECT_BY_PATH(parent_id, '/') Parent_Path
FROM tree_hierarchy
WHERE CONNECT_BY_ISLEAF<>0
  CONNECT BY PRIOR id = PARENT_id
START WITH id = 2
ORDER SIBLINGS BY ID;
于 2013-07-12T11:56:30.740 回答