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

时间:2015-12-17 09:00:43

标签: sql postgresql

在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'
}]

我是否总是要做两个选择查询,并通过使用别名将一个插入到另一个? 你能举个例子说明:你如何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",
)

1 个答案:

答案 0 :(得分:2)

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

我按照here中的教程。

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