在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父表及其子表一起显示?
SELECT
UPD 1 :
SELECT "public"."ParentTable".*, "public"."ChildTable".* FROM "public"."ParentTable" RIGHT JOIN "public"."ChildTable" ON "public"."ParentTable"."childReference"
返回此:
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中的一项新功能,但我没有测试查询:
我从这里开始学习本教程。
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