微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我的家谱包含孩子和父母。我可以编写一个查询,使用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

解决方法

这可以做到:

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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。