如何在 PostgreSQL table 中获取相关数据?

How do I get related data in PostgreSQL table?

在我的 PostgreSQL 数据库中,我有 table 具有这样的结构:

| organization_id | organization_name | parent_organization_id | tree_organization_id |
|-----------------|-------------------|------------------------|----------------------|
| 1               | Alphabet          |                        |                      |
| 2               | Google            | 1                      |                  |
| 3               | Google X          | 2                      |                |

如您所见,table 存储了组织之间的层次关系。假设我有一个 id 数组作为输入。为简单起见,假设我有以下数组 [3]。如何从数组中获取所有上级组织的列表?就我而言,我想看到的最终结果是:

| organization_id | organization_name | parent_organization_id | tree_organization_id |
|-----------------|-------------------|------------------------|----------------------|
| 1               | Alphabet          |                        |                      |
| 2               | Google            | 1                      |                  |

我需要关注 tree_organization_id 列还是递归遍历 parent_organization_id 列?

PostgreSQL 版本:

PostgreSQL 11.4 (Debian 11.4-1.pgdg90+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit

列类型:

| Column name            | Column type |
|------------------------|-------------|
| organization_id        | int8        |
| organization_name      | varchar     |
| parent_organization_id | int8        |
| tree_organization_id   | varchar     |

这两种方式你都可以遵循,我更愿意递归迭代parent_organisation_id

下面是查询。

select * from company where
    organization_id in( select parent_organization_id
                       from company where parent_organization_id is not null);

你可以找到 working example from here

使用Common Table Expression(CTE)列出所有父子关系。在 CTE 的帮助下,您可以删除 tree_organization_id 列。

link 为 CTE 初学者提供了很好的教程。