我正在尝试并在Oracle 11g数据库的一个重要查询中搜索从节点获取所有最后一级子项(leafs)的方式。
我有两个表:“节点”(所有节点的列表及其各自的值),以及指定父子关系的“关系”:
ID_NODE - VALUE
1 3
2 6
3 9
4 2
5 4
6 5
7 2
8 7
9 8
10 1
ID_FATHER - ID_CHILD
1 2
1 3
1 4
2 5
2 6
4 7
5 8
5 9
7 10
我读过有关CONNECT_BY_ISLEAF的内容,如果它是一个叶子,则返回1,但我不能像Oracle示例那样查询CONNECT_BY_ISLEAF,而且我得不到任何结果。即使我不知道如何使用此函数准确地进行查询(例如使用案例条件?)
太多了!
答案 0 :(得分:9)
我认为,这样的事情应该可以解决问题:
SELECT * FROM
(SELECT n.id, n.val, CONNECT_BY_ISLEAF isleaf FROM NODES n
LEFT JOIN RELATION r ON n.id = r.id_child
CONNECT BY PRIOR n.id = r.id_father
START WITH r.id_father IS NULL)
WHERE isleaf = 1
哦,顺便说一句,你甚至可以在不使用hierahical查询的情况下获得所有叶子。只需选择所有节点,这些节点不是关系表中任何节点的父节点。这样的事情:
SELECT n.* FROM NODES n
WHERE NOT EXISTS (SELECT ID_FATHER FROM RELATION r
WHERE r.id_father = n.id)
为了从指定节点获取叶节点,只需在START WITH子句中更改条件,从您感兴趣的节点开始树反向。例如,此查询将返回所有子节点的叶子id = 5:
SELECT * FROM
(SELECT n.id, n.val, CONNECT_BY_ISLEAF isleaf FROM NODES n
LEFT JOIN RELATION r ON n.id = r.id_child
CONNECT BY PRIOR n.id = r.id_father
START WITH n.id = 5)
WHERE isleaf = 1
答案 1 :(得分:1)
您只需使用CONNECT_BY_ISLEAF即可。
SELECT n.id, n.val
FROM NODES n
LEFT JOIN RELATION r ON (n.id = r.id_child)
WHERE CONNECT_BY_ISLEAF = 1
CONNECT BY PRIOR n.id = r.id_father
START WITH r.id_father IS NULL