我想创建SELECT
个实体和一个uploads
JSON数组列,其中包含它们的所有上载以及每个上载的cover
和profile
字段。
到目前为止,我可以获取上传数组,但是我无法从entitiesXuploads
表中添加另外两个字段。
我的三个表的基本表示如下:
Entities
Uploads
entitiesXuploads
我的查询:
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
哪个行返回:
答案 0 :(得分:1)
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()
聚合函数将记录分组,以将这些对象合并为一个数组。