相关疑难解决方法(0)

在单个查询中从一对多关系数据构建 JSON 对象?

我有一个带有如下表的 PostgreSQL 9.5.3 DB:

container
    id: uuid (pk)
    ... other data

thing
    id: uuid (pk)
    ... other data

container_thing
    container_id: uuid (fk)
    thing_id: uuid (fk)
    primary key (container_id, thing_id)
Run Code Online (Sandbox Code Playgroud)

Acontainer可以指向任意数量的things(没有重复),并且 athing可以被任意数量的containers指向。

可能有大量的容器和东西(取决于我们有多少客户)。每个容器中可能只有 1 到 10 个东西。我们一次最多只能查询大约 20 个容器。一个容器可以是空的,我需要取回一个空数组。

我需要构建代表容器的 json 对象,如下所示:

{
    "id": "d7e1bc6b-b659-432d-b346-29f3a530bfa9",
    ... other data
    "thingIds": [
        "4e3ad81b-f2b5-4220-8e0e-e9d53c80a214",
        "f26f49e5-76b4-4363-9ffe-9654ba0b0f0d"
    ]
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我通过使用两个查询来做到这一点:

select * from "container" where "id" in (<list of container ids>)
select * from "container_thing" where "container_id" in …
Run Code Online (Sandbox Code Playgroud)

postgresql join array json many-to-many

9
推荐指数
1
解决办法
3万
查看次数

标签 统计

array ×1

join ×1

json ×1

many-to-many ×1

postgresql ×1