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

标签 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'
}]

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

更新 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",
)

最佳答案

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

关于sql - 如何从 PostgreSQL 的子表中选择数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34319165/

相关文章:

postgresql - PostGIS 中的大陆/国家边界(多边形与线串)

sql - 我们可以在另一个存储过程中编写一个子函数或过程吗

sql - 在count sql中包含0

python - 在 python 2.7.5 中使用来自 cx_Oracle 模块的函数 callproc 执行脚本

sql - 如何列出与特定表相关的所有表名

javascript - 意外的 JavaScript 日期结果

ruby-on-rails - ActiveRecord::Relation 等效于 Array#delete_at(index) 的方法?

postgresql - 如何停止在 PostgreSQL 中对表进行聚类

json - Jooq Postgres JSON 查询

mysql - 如何进行 "users who like X also like Y"查询?