Postgres

时间:2018-06-15 17:33:46

标签: sql json postgresql jsonb

我有一个4层次的层次结构,我希望将其检索到最高级别。

让我们说你有班级 - >订单 - >家庭 - >物种。

我正在寻找以下输出:

{ 
  classes: [{
    id: 1,
    name: "Class A",
    orders: [{
      id: 1,
      name: "Class A - Order 1",
      families: [{
        id: 1,
        name: "Class A - Order 1 - Family I"
        species: [{
          id: 1,
          name: "Class A - Order 1 - Family I - Species 1"
        }]
      }]
    }]
  }]
}

使用大规模连接也很容易获取数据

SELECT classes.id as class_id, orders.id as order_id, families.id as family_id, species.id as species_id
FROM species
JOIN families ON families.id = species.family_id
JOIN orders ON orders.id = families.order_id
JOIN classes ON classes.id = orders.class_id

但是这会产生平坦的桌面结构,而不是我正在寻找的卷起的结构。

class_id order_id family_id species_id
1        1        1         1
1        1        1         2
1        1        1         3

我尝试使用LATERAL个连接,这些连接是在上下文中评估的子查询。所以有一些事情:

SELECT classes.id, array_agg(orders_sub.id) as orders
FROM classes,
LATERAL (
  SELECT orders.id
  FROM orders
  WHERE classes.id = orders.class_id
) AS orders_sub
group by classes.id;

产生:

id  orders
1   {1,2}

但是我无法降低多个级别并累积整个记录。

奖励:如果我们可以消除空关系的元素,例如没有任何物种的家庭会很棒。

背景:这是一个报告API,到目前为止我们一直在序列化Rails ActiveRecord对象,对于大量数据(我认为通常为100k-1M范围)显然非常慢。所以我喜欢利用Postgres提供的JSON功能

1 个答案:

答案 0 :(得分:1)

Json是所需结构化输出的唯一合理格式。您必须构建分层查询以获得结构化层次结构。

select
    jsonb_agg(jsonb_build_object(
        'id', id, 
        'class', name, 
        'orders', orders)
        order by id
    ) as classes
from classes
join (
    select
        class_id,
        jsonb_agg(jsonb_build_object(
            'id', id, 
            'order', name, 
            'families', families)
            order by id
        ) as orders
    from orders
    join (
        select 
            order_id, 
            jsonb_agg(jsonb_build_object(
                'id', id, 
                'family', name,
                'species', species)
                order by id
            ) as families
        from families
        join (
            select 
                family_id, 
                jsonb_agg(jsonb_build_object(
                    'id', id, 
                    'species', name)
                    order by id
                ) as species
            from species
            group by family_id
            ) s on id = family_id
        group by order_id
        ) f on id = order_id
    group by class_id
    ) o on id = class_id

请参阅示例数据的演示:DbFiddle.