递归查询中的排序结果

时间:2018-07-15 12:43:38

标签: sql json postgresql recursive-query jsonb

我有一个基本的类别表格,由 primary_key parent_id title 排序整数。

我能够使用CTE检索结果并将其转换为json数组,但我想根据排序值除parent_id以外获取它们。

到目前为止:

with recursive parents as
(
    select n.boat_type_id, n.title, '{}'::int[] as parents, 0 as level
    from boat_types n
    where n.parent_id is NULL
    union all
    select n.boat_type_id, n.title, parents || n.parent_id, level+1
    from parents p
        join boat_types n on n.parent_id = p.boat_type_id
    where not n.boat_type_id = any(parents)
),
children as
(
    select n.parent_id, json_agg(jsonb_build_object('title', n.title->>'en'))::jsonb as js
    from parents tree
        join boat_types n using(boat_type_id)
    where level > 0 and not boat_type_id = any(parents)
    group by n.parent_id
    union all
    select n.parent_id, jsonb_build_object('category', n.title->>'en') || jsonb_build_object('subcategories', js) as js
    from children tree
        join boat_types n on n.boat_type_id = tree.parent_id
)
select jsonb_agg(js) as categories
from children
where parent_id is null  

以上内容为我提供了所需的结果集和结构,但是如何使它们遵循节点和叶子的排序值。

示例响应:

[
   {
      "sorting":0,
      "category":"Motor",
      "subcategories":[
         {
            "title":"Motor Yacht",
            "sorting":2
         },
         {
            "title":"Mega Yacht",
            "sorting":1
         }
      ]
   },
   {
      "sorting":1,
      "category":"Sailing",
      "subcategories":[
         {
            "title":"Sailing Yacht",
            "sorting":2
         },
         {
            "title":"Cruiser Racer",
            "sorting":1
         }
      ]
   },
   {
      "sorting":2,
      "category":"Catamaran",
      "subcategories":[
         {
            "title":"Catamaran",
            "sorting":2
         },
         {
            "title":"Trimaran",
            "sorting":1
         }
      ]
   },
   {
      "sorting":3,
      "category":"Other",
      "subcategories":[
         {
            "title":"Other",
            "sorting":2
         },
         {
            "title":"Airboat",
            "sorting":1
         }
      ]
   }
]

我尝试汇总ARRAY字段中的排序值并按其排序,但这是行不通的。

1 个答案:

答案 0 :(得分:0)

您可以在order by聚合中使用json_agg()子句:

...
children as
(
    select 
        n.parent_id, 
        json_agg(jsonb_build_object('title', n.title->>'en', 'sorting', n.sorting) order by n.sorting)::jsonb as js
    from parents tree
        join boat_types n using(boat_type_id)
    where level > 0 and not boat_type_id = any(parents)
    group by n.parent_id
    union all
    select 
        n.parent_id, 
        jsonb_build_object('category', n.title->>'en', 'sorting', n.sorting) || jsonb_build_object('subcategories', js) as js
    from children tree
        join boat_types n on n.boat_type_id = tree.parent_id
)
...