小编典典

如何从PostgreSQL的子表中选择数据?

sql

在PostgreSQL 9.4中,我如何像这样检索json对象:

parentTableFirstProp: 'string',
parentToChildReference: [
    {childTableFirstProp: 'another string'},
    {childTableFirstProp: 'yet another string'}
}]

而不是这样:

[{
    parentTableFirstProp: 'string',
    childTableFirstProp: 'another string',
},{
    parentTableFirstProp: 'string',
    childTableFirstProp: 'yet another string'
}]

我是否总是必须进行2个选择查询,并通过使用别名将一个查询插入另一个查询?您能否举一个例子:您如何将SELECT父表及其子表一起显示?

UPD 1

SELECT
"public"."ParentTable".*,
"public"."ChildTable".*
FROM
"public"."ParentTable"
RIGHT JOIN "public"."ChildTable"
ON "public"."ParentTable"."childReference"

返回此:

[{
        parentTableFirstProp: 'string',
        childTableFirstProp: 'another string',
    },{
        parentTableFirstProp: 'string',
        childTableFirstProp: 'yet another string'
    }]

UPD 2
创建表语句:

CREATE TABLE "public"."ParentTable" (
    "id" varchar(36) NOT NULL COLLATE "default",
    "parentTableFirstProp" varchar(100) NOT NULL COLLATE "default",
    "parentToChildReference" varchar COLLATE "default"
)

CREATE TABLE "public"."ChildTable" (
    "id" varchar(36) NOT NULL COLLATE "default"
    "childTableFirstProp" varchar(100) NOT NULL COLLATE "default",
)

阅读 158

收藏
2021-04-14

共1个答案

小编典典

PostgreSQL 9.2中的一项新功能,但我没有测试查询:

我从这里开始学习本教程。

select row_to_json(t)
from (
select ParentTable.parentTableFirstProp, (
select array_to_json(array_agg(row_to_json(child)))
  from (
    select childTableFirstProp
    from ChildTable
    where ChildTable.id=ParentTable.parentToChildReference
  ) child

  ) as parentToChildReference
from ParentTable
) t
2021-04-14