这是数据集,代表树的分支。显然,节点3,5是叶节点。
branch_of_tree
1
1/2
1/2/3
1/2/4
1/2/4/5
我打算找到所有叶子节点,所以对于上面的例子,它应该是节点3和节点5.有谁能让我知道如何在PostgreSQL中解决它?谢谢!
答案 0 :(得分:1)
可能类似以下内容:
SELECT t.branch_of_tree
FROM tree t
WHERE NOT EXISTS
(SELECT 1
FROM tree t2
WHERE t.branch_of_tree <> t2.branch_of_tree
AND position(t.branch_of_tree in t2.branch_of_tree) = 1);
┌────────────────┐
│ branch_of_tree │
├────────────────┤
│ 1/2/3 │
│ 1/2/4/5 │
└────────────────┘
(2 rows)
答案 1 :(得分:1)
尝试此查询:
SELECT Tb.* FROM T as Tb
WHERE NOT EXISTS (SELECT * FROM T WHERE
T.branch_of_tree LIKE Tb.branch_of_tree || '%'
AND T.branch_of_tree <> Tb.branch_of_tree )