postgres - 递归

时间:2013-01-23 23:47:18

标签: sql postgresql recursive-query

我希望以下内容返回所有元组,将层次结构中的每个父级解析到顶部,但它只返回最低级别(其ID在查询中指定)。如何返回给定level_id的整个树?

create table level(
level_id int,
level_name text,
parent_level int);

 insert into level values (197,'child',177), (  177, 'parent', 3 ), (  2, 'grandparent',  null  );

WITH RECURSIVE recursetree(level_id, levelparent) AS (
 SELECT level_id, parent_level 
 FROM level 
 where level_id = 197

UNION ALL
SELECT t.level_id, t.parent_level
FROM level t, recursetree rt 
WHERE rt.level_id = t.parent_level
)

SELECT * FROM recursetree;

1 个答案:

答案 0 :(得分:7)

首先,如果(2, 'grandparent', null)真的是祖父母,那么(3, 'grandparent', null)应为rt.levelparent。其次,您的查询的递归半部分中的(隐式)连接条件是向后的,您希望从t.parent_level而不是WITH RECURSIVE recursetree(level_id, levelparent) AS ( SELECT level_id, parent_level FROM level WHERE level_id = 197 UNION ALL SELECT t.level_id, t.parent_level FROM level t JOIN recursetree rt ON rt.levelparent = t.level_id -- join condition fixed and ANSI-ified above ) SELECT * FROM recursetree; 获取父级:

{{1}}