【问题标题】:Use Postgres RECURSIVE to create a view of descendants使用 Postgres RECURSIVE 创建后代视图
【发布时间】:2017-05-17 14:12:31
【问题描述】:

我正在尝试创建一个 postgres 视图,其中包含一种分层结构的哈希映射。

我的层次结构表看起来像:

------------------
| id | parent_id |
------------------
|  1 |      null |
|  2 |         1 |
|  3 |         1 |
|  4 |         2 |

出于性能原因,我需要在我的程序代码中使用散列表示

1 => [2,3,4]; 2 => [4]; ...

我可以通过这个查询得到 1 的所有孩子:

WITH RECURSIVE
    h_tree(id, label)
  AS (
    SELECT
      id,
      label
    FROM hierarchy
    WHERE parent_id = 10000
    UNION ALL
    (
      SELECT
        h.id,
        h.label
      FROM h_tree v, hierarchy h
      WHERE h.parent_id = v.id
    )
  )
SELECT array_to_json(ARRAY_AGG(id)) AS children_ids
FROM h_tree

这个查询给了我一个“10000”的所有孩子的(json 编码)列表。

我的问题:

我如何将其包装在此查询的输出为的表单中

---------------------------------
| hierarchy_id | children_ids[] |
---------------------------------
|            1 |        [2,3,4] |

非常感谢!

编辑

我的问题有误。我需要所有的后代,感谢@pozsfor 指出这一点。

此外,我的示例有缺陷,我对其进行了编辑。

【问题讨论】:

  • 也许使用Select label as hierarchy_ID, string_agg(id,',') From h_tree group by label 而不是array_to_jason 为每个hierarchy_ID/label 将多行合并为一行?我有点困惑,因为我看不到 hierarchy_ID 来自哪里,除非它是标签。
  • 需要一个RECURSIVE 查询所有后代。对于儿童,您只需要一个简单的JOIN(或者更确切地说,如果您不需要除儿童的id 之外的任何东西,则只需一个简单的SELECT)。前任rextester.com/VGTKE62744
  • 谢谢,但我没有在问题中说清楚,我需要所有的后代,不仅仅是孩子。

标签: sql performance postgresql recursive-query


【解决方案1】:
WITH RECURSIVE children AS
   (SELECT parent_id AS id, id AS child_id
    FROM hierarchy
    WHERE parent_id IS NOT NULL
    UNION
    SELECT children.id, h.id
    FROM children
      JOIN hierarchy h
         ON h.parent_id = children.child_id
   )
SELECT hierarchy.id,
       string_agg(children.child_id::text, ',')
FROM hierarchy
   LEFT JOIN children USING (id)
GROUP BY hierarchy.id;

┌────┬────────────┐
│ id │ string_agg │
├────┼────────────┤
│  1 │ 2,3,4      │
│  2 │ 4          │
│  3 │            │
│  4 │            │
└────┴────────────┘
(4 rows)

【讨论】:

  • 感谢您的回答,但我的问题有误。希望你能再看看:)
  • 我重写了已更改问题的答案。
  • 非常感谢!完美运行! (而且快得要死)
猜你喜欢
  • 2022-01-15
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 2016-03-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
相关资源
最近更新 更多