sql:循环查询结果

xxb16uws  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(395)

关于postgresql中的公司树
我用下面的公式得到id=11的公司的子公司。

SELECT * FROM "OwnershipTable" 
WHERE "Parent_ID" = 11;

给我以下输出
公司名称母公司名称母公司名称母公司名称控股公司111TopCo112Holdco211TopCo113Holdco311TopCo114Holdco411TopCo
不过,我想调查一下控股公司是否有子公司。因此,我的问题是:是否可以使用某种循环在查询中插入列“company\u id”作为“parent\u id”?

fgw7neuy

fgw7neuy1#

对。这称为递归cte:

with recursive cte as (
      select company_id as parent_company_id, company_id as child_id
      from OwnershipTable ot
      where parent_id = 11
      union all
      select cte.parent_company_id, ot.company_id
      from cte join
           OwnershipTable ot
           on ot.parent_id = cte.child_id
     )
select *
from cte;

如果你想了解这些公司的更多信息,你可以 join 它包含在递归cte定义中。

k5hmc34c

k5hmc34c2#

这应该起作用:

SELECT * FROM "OwnershipTable" ot
    WHERE EXISTS(SELECT 1 FROM "OwnershipTable" where Parent_ID = ot.Company_ID)

相关问题