Postgres:选择数据到jsonb对象

时间:2019-05-20 08:06:37

标签: postgresql-9.6

我是Postgres中json的新手,所以请不要向我扔任何东西。我正在尝试选择数据到jsonb对象。我计划将其用于select的更新。现在看起来像这样:

select to_jsonb(full_address) as full_address
from (
         select "user".living_addr      as living_id,
                "user".living_addr_path as living_path,
                null                    as living_house,

                "user".address_level_id as registration_id,
                "user".address_path     as registration_path,
                null                    as registration_house,

                "user".work_addr      as work_id,
                "user".work_addr_path as work_path,
                null                  as work_house,

                public."user".user_id

         from public."user"
     ) full_address
group by user_id, full_address
order by user_id

但是我还需要将“ living_id”,“ living_path”,“ living_house”放入这样的对象中:

{
    "living": {"id", "path", "house"}
}

,用于注册,工作和学习。

此外,我在结果对象中不需要user_id。

试图使用子查询,例如:

select to_jsonb(living)            as living,
       to_jsonb(registration)      as registration,
       ...
from (
    select "user".living_addr      as id,
           "user".living_addr_path as path,
           null                    as house
    from public."user"
) living,
(
    select "user".address_level_id as id,
           "user".address_path     as path,
           null                    as house
    from public."user"
) registration
... etc

但是,现在如果不进行分组,结果将是错误的,而且我找不到在其中使用分组依据的线索。我应该有另外一种更简单的方法。

结果对象应如下所示:

{
    "work": {"id": ..., "path": [..., ...], "house": null}, 
    "living": {"id": ..., "path": [..., ...], "house": null}, 
    "registration": {"id": ..., "path": [..., ...], "house": null}
}

在postgres 9.6中有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

是的,它要简单得多:

select jsonb_build_object(
               'registration', jsonb_build_object('id', u.address_level_id, 'path', u.address_path, 'house', null),
               'living', jsonb_build_object('id', u.living_addr, 'path', living_addr_path, 'house', null),
               'work', jsonb_build_object('id', u.work_addr, 'path', u.work_addr_path, 'house', null)
           )
from public.user u

无需从选择中进行更新,只需更新即可。