我有 PostgreSQL 表,其中记录存储为树值
我想在孩子询问时得到所有家长的来信 例子:
WITH RECURSIVE generation AS (
SELECT node_id,
entity_id,
letter,
parent_id,
0 AS generation_number
FROM doitestchk
WHERE parent_id IS NULL
UNION ALL
SELECT child.node_id,
child.entity_id,
child.letter,
child.parent_id,
generation_number+1 AS generation_number
FROM doitestchk child
JOIN generation g
ON g.node_id = child.parent_id
)
SELECT entity_id,
letter,
generation_number
FROM generation
WHERE letter like '%a0314%';
我只得到node_id:5 相反,我需要node_id : 5 的所有父节点,即node_id 3 ,它是node_id :1 的子节点
有什么方法可以获取子节点的所有父节点。
您的查询从上到下(父级 -> 子级)遍历树,但是从特定子节点搜索时需要找到所有父节点。
此查询将返回层次结构中的所有父节点,从目标节点开始并在树结构中向上移动:
WITH RECURSIVE parent_hierarchy AS (
-- Base: start from target node
SELECT
node_id, entity_id, letter, parent_id, 1 as level
FROM doitestchk
WHERE letter LIKE '%a0314%'
UNION ALL
-- Recursive: find parents
SELECT
p.node_id, p.entity_id, p.letter, p.parent_id, ph.level + 1
FROM doitestchk p
JOIN parent_hierarchy ph ON p.node_id = ph.parent_id
)
SELECT *
FROM parent_hierarchy
ORDER BY level DESC;