计算分层postgresql结构中的子类别数

时间:2018-01-15 15:47:27

标签: postgresql

我有一个包含类别(id,name,parent_id)的表,而parent_id是一个上层类别的id。 我通过以下查询得到了我的类别树:

 WITH RECURSIVE query AS (
    SELECT id, name, parent_id
    FROM category  
        UNION all
    SELECT s2.id, s2.name, s2.parent_id
    FROM category  s2 join query on query.id= s2.parent_id 
)
SELECT * from query order by parent_id;

如何计算表格中的子类别?

1 个答案:

答案 0 :(得分:1)

我相信跟踪递归的depth会给你答案。我几乎总是在我的递归CTE中添加depthpath,因为它是一个快速添加,它们在结果集中提供了大量有用的信息:

WITH RECURSIVE query AS (
    SELECT id, name, parent_id, 1 as depth, CAST(id || '>' || parent_id as VARCHAR(500)) as path
    FROM category  
        UNION all
    SELECT s2.id, s2.name, s2.parent_id, query.depth + 1, query.path || '>' || s2.parent_id
    FROM category  s2 join query on query.id= s2.parent_id 
)
SELECT * from query order by depth, path;

这可能无法满足您的需求,但您也可以在最终查询中COUNT()

SELECT parent_id, count(*) from query GROUP BY parent_id; 

哪个应该为你提供每个parent_id的递归结果集中的记录计数,理论上应该是子计数,对吗?