递归的Postgres-结果包括祖父母和孙子女

时间:2020-08-20 14:04:07

标签: postgresql recursive-query with-statement

我的家谱包含孩子和父母。我可以编写一个查询,使用postgres $("#getProcess").bind("click", function () { $.getJSON($SCRIPT_ROOT + "/get_process", function (data) { $(data).each(function (i,full) { $("#result").append(`<tr><td id="data_id">` + full.id + `</td><td><input type="text" name=firstName id="firstName" value=`+ full.firstName +`>` +`</td><td><input type="text" name=lastName id="lastName" value=`+ full.lastName +`></td><td>`+ `<button id="update-button">Update</button>` ); //update-button id to update selected row }); }); }); $("#update-button").bind("click", function () { $.getJSON($SCRIPT_ROOT + '/update_process',{ firstName: $('input[name="firstName"]').val(), lastName: $('input[name="lastName"]').val() }, function (data) { $("#result").text(data.result) }); }); 返回给定人的孙代。但是,如何在结果中包括祖父母?我的目标是报告按祖父母id分组的孙子代数。如何在最终结果中引用查询的非递归部分?


已编辑-示例表:

with recursive

查询的非递归部分:

child parent
  11   null
  12   null
  13   null
  21    11
  22    11
  31    12
  32    12
  33    12
  41    13
  81    21
  82    21
  83    21
  91    33
  92    33

所需结果:

select distinct child where parent is null -- as grandparent

1 个答案:

答案 0 :(得分:1)

这可以做到:

with recursive zzz AS (
  select child AS grandparent, child AS current_child, 1 AS grand_level 
  FROM thetable AS tt
  where parent is null
 UNION
  SELECT grandparent, tt.child, grand_level+1
  FROM thetable AS tt
  JOIN zzz
    ON tt.parent = zzz.current_child
)
SELECT grandparent, COUNT(DISTINCT current_child)FILTER(WHERE grand_level = 3) AS grandchildren
FROM zzz
GROUP BY grandparent;