2016-06-17 33 views
2

我需要創建一個返回分層json結果的SQL查詢(postgres 9.5.3)。這是我寫到目前爲止的代碼返回json單個SQL查詢中的分層結構

WITH RECURSIVE q AS ( 
    WITH c AS (
     SELECT pc."Id", pc."Description" 
     FROM "ProductCategories" pc 
     WHERE pc."Active" = true 
    ) 
    SELECT pc, ARRAY[c] as "Children", ARRAY[pc."Id"] as "Path" 
    FROM "ProductCategories" pc 
    LEFT JOIN c ON pc."Id" = c."Id" 
    WHERE NULLIF(pc."ParentId", 0) IS NULL 
    AND pc."Active" = true 
    UNION ALL 
    SELECT pc_descendant, array_append(q."Children", c), q."Path" || pc_descendant."Id" 
    FROM q 
    JOIN "ProductCategories" pc_descendant ON pc_descendant."ParentId" = (q.pc)."Id" 
    LEFT JOIN c ON pc_descendant."Id" = c."Id" 
    WHERE pc_descendant."Active" = true 
) 
SELECT * FROM q 

我有問題創建分層對象Children。對於這些結構

A 
    B 
     C 
D 
    E 

array_append功能似乎添加任何孩子元素融入到一個數組:

A.Children = [ {B}, {C}, {D} ] //for category A 

我需要的結構:

A.Children = [ {B, Children = [ {C, Children = [ {D} ] } ] } ] 

我怎樣才能改變我的查詢來實現這一? Regards

回答

2

不確定這是可能的,至少在簡單方便的方式。

但是,它似乎很簡單,使用「真正的」遞歸。

下面是簡單的例子:

create temp table t(id int, parent int, name text) on commit drop; 

insert into t values 
    (1,null,'john'), 
    (2,1,'jane'), 
    (3,1,'jack'), 
    (4,2,'julian'); 

create or replace function build_family(p_parent int) returns setof jsonb as $$ 

    select jsonb_build_object('name', t.name, 'family', jsonb_agg(f.x)) 
    from t left join build_family(t.id) as f(x) on true 
    where t.parent = p_parent or (p_parent is null and t.parent is null) 
    group by t.id, t.name; 

$$ language sql; 

select * from build_family(null::int); 

和結果是

{"name": "john", "family": [{"name": "jane", "family": [{"name": "julian", "family": [null]}]}, {"name": "jack", "family": [null]}]} 

我希望你能適應它爲您的數據。

祝你好運。