从oracle中的CONNECT-BY查询中删除重复的子树

时间:2013-07-12 11:00:53

标签: sql database oracle

我有一个格式为

的层次表
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 Query,它只能让我这个

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

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

这是一个更简单的例子我有这样的1000条记录。当我运行上面的查询时,它生成了许多重复项。任何人都可以给我一个通用查询,它将提供从leaf到root的完整路径duplicates.Thanks提前帮助

2 个答案:

答案 0 :(得分:3)

必须始终知道有限层次结构中的根节点。 根据定义: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;

答案 1 :(得分:0)

你应该明确指出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
WHERE CONNECT_BY_ISLEAF<>0
  CONNECT BY PRIOR id = PARENT_id
START WITH id = 2
ORDER SIBLINGS BY ID;