合并两个联接的表并输出为JSON?

时间:2019-05-17 11:54:36

标签: json postgresql jsonb pg

我想创建SELECT个实体和一个uploads JSON数组列,其中包含它们的所有上载以及每个上载的coverprofile字段。

到目前为止,我可以获取上传数组,但是我无法从entitiesXuploads表中添加另外两个字段。

我的三个表的基本表示如下:

Entities

  • id(int8)
  • 名称(varchar)

Uploads

  • id(uuid)
  • 标题(varchar)
  • 版本(jsonb)

entitiesXuploads

  • entityId(int8)
  • uploadId(uuid)
  • 封面(布尔)
  • 个人资料(布尔)

我的查询:

SELECT
    e.id,
    e.name,
    COALESCE(jsonb_agg(up) FILTER (WHERE up."id" IS NOT NULL), '[]') as uploads

FROM 
    entities as e
    LEFT JOIN "entitiesXuploads" as exu ON exu."entityId" = e."id"
    LEFT JOIN "uploads" as up ON up."id" = exu."uploadId"

GROUP BY
    e.id,
    e.name

哪个行返回:

  • id(实体ID)
  • 名称(实体名称)
  • 上传(上传的json数组)

1 个答案:

答案 0 :(得分:1)

demo: db<>fiddle

SELECT 
    e.id,
    e.name,
    jsonb_agg(
        jsonb_build_object(
            'upload_id', upload_id, 
            'title', title, 
            'versions', versions,
            'cover', cover,
            'profile', profile
        )
    ) AS uploads
FROM
    entities e
JOIN entities_uploads eu ON e.id = eu.entity_id
JOIN uploads u ON eu.upload_id = u.id
GROUP BY e.id, e.name

您可以使用jsonb_build_object()创建每个记录所需的对象。之后,您可以使用jsonb_agg()聚合函数将记录分组,以将这些对象合并为一个数组。