Postgres函数 - 从多个查询中组成对象数组。

问题描述 投票:0回答:1

我这里有以下数据集

create table categories(
    id serial primary key,
    parent_id integer,
    name varchar(255) not null
);
create table entry(
    id serial primary key,
    location_id varchar(255) not null,
    location_string varchar(255) not null
);
create table entry_type(
    id serial primary key,
    name varchar(255) not null,
    category_ids integer[]
);
insert into categories(parent_id,name) values
(null,'a'), (null,'b'),(null,'c'), (1,'d'), (2,'e'), (5,'f');

insert into entry_type(name, category_ids) values
('entry_type_1', '{1}'),('entry_type_2', '{4, 3}'),('entry_type_3', '{5, 6}'),('entry_type_1', '{6}');

insert into entry(location_id, location_string) values
('1/4','a/d'),('2','b'),('5/6','e/f'),('5/6','e/f');

我正在运行这个查询。

select
    json_build_object(
            'id', u.id,
            'name', u.name,
            'parent_id', u.parent_id,
      'entry_type', json_agg(json_build_object(
                    'id', ur.id,
                    'name', ur.name
                )),
            'entries', json_agg(json_build_object(
                    'id', en.location_string
                ))
        )
from public.categories u
join public.entry_type ur on u.id = any(ur.category_ids)
join public.entry en on en.location_id like concat(u.id::text, '%')
group by u.id;

(下面是一个... 抚弄 为所有这些)。)

但我想创建一个Postgres函数,将返回结果(JSON),如下所述。

在我的查询中,我选择了所有的类别,但是我需要添加一个条件,例如:可以是NULL,也可以是另一个idinteger。parent_id = "function_param" 可以是NULL,或者是另一个idinteger。

[
  {
    "id": "1",
    "name": "a",
    "parent_id": null,
    "entry_types": [
      {
        "id": "18"
      }
    ],
    "entries": [
      {
        "id": "54"
      },
      {
        "id": "22"
      }
    ],
    "entries_count": 2,
    "entry_types_count": 1
  },
  {
    "id": "2",
    "name": "b",
    "parent_id": null,
    "entry_types": [
      {
        "id": "88"
      }
    ],
    "entries": [
      {
        "id": "28"
      }
    ],
    "entries_count": 1,
    "entry_types_count": 1
  }
]
postgresql graphql postgresql-9.4 postgraphile
1个回答
0
投票

只要在你的查询周围加上一个 json_agg:

SELECT json_agg(j)
FROM (SELECT json_build_object(...) AS j
      FROM public.categories
      ...
     ) AS subq;
© www.soinside.com 2019 - 2024. All rights reserved.