[英]Generate single complex JSON object from PostgreSQL query
我有一个 PostgreSQL 数据库,其中包含以下表格:
Building
ID | 姓名 | 描述 |
---|---|---|
1 | 1号楼 | 第一栋建筑说明 |
2 | 2号楼 | 2楼描述 |
3 | 3号楼 | 3楼描述 |
Floor
ID | 姓名 | 描述 | BUILDING_ID |
---|---|---|---|
1 | 1.1层 | 楼层说明 1.1 | 1 |
2 | 1.2楼 | 楼层说明 1.2 | 1 |
3 | 2.1楼 | 楼层说明 2.1 | 2 |
4 | 2.2楼 | 楼层说明 2.2 | 2 |
5 | 3.1楼 | 楼层说明 3.1 | 3 |
Room
ID | 姓名 | 描述 | FLOOR_ID |
---|---|---|---|
1 | 房间 1.1.1 | 房间描述 1.1.1 | 1 |
2 | 房间 1.1.2 | 房间描述 1.1.2 | 1 |
3 | 房间 1.2.1 | 房间描述 1.2.1 | 2 |
4 | 房间 1.2.2 | 房间描述 1.2.2 | 2 |
5 | 房间 3.1.1 | 房间描述 2.1.1 | 5 |
生成上述结构的代码可以在这个SQL Fiddle中找到, here 。
我想用一个查询生成一个 JSON object,结构如下:
{
"Building 1": {
"details": {
"id": 1,
"name": "Building 1",
"description": "1st Building Description"
},
"floors": {
"Floor 1.1": {
"details": {
"id": 1,
"name": "Floor 1.1",
"description": "Floor Description 1.1"
},
"rooms": {
"Room 1.1.1": {
"id": 1,
"name": "Room 1.1.1",
"description": "Room Description 1.1.1"
},
"Room 1.1.2": {
"id": 2,
"name": "Room 1.1.2",
"description": "Room Description 1.1.2"
}
}
},
"Floor 1.2": {
"details": {
"id": 2,
"name": "Floor 1.2",
"description": "Floor Description 1.2"
},
"rooms": {
"Room 1.2.1": {
"id": "3",
"name": "Room 1.2.1",
"description": "Room Description 1.2.1"
},
"Room 1.1.2": {
"id": 4,
"name": "Room 1.2.2",
"description": "Room Description 1.2.2"
}
}
},
}
},
"Building 2": {
"details": {
"id": 2,
"name": "Building 2",
"description": "2nd Building Description"
},
"floors": {
"Floor 2.1": {
"details": {
"id": 3,
"name": "Floor 2.1",
"description": "Floor Description 2.1"
},
"rooms": {
}
},
"Floor 2.2": {
"details": {
"id": 4,
"name": "Floor 2.2",
"description": "Floor Description 2.2"
},
"rooms": {
}
},
}
},
"Building 3": {
"details": {
"id": 3,
"name": "Building 3",
"description": "3rd Building Description"
},
"floors": {
"Floor 3.1": {
"details": {
"id": 5,
"name": "Floor 3.1",
"description": "Floor Description 3.1"
},
"rooms": {
"Room 3.1.1": {
"id": 5,
"name": "Room 3.1.1",
"description": "Room Description 3.1.1"
}
}
}
}
},
}
解释上面的结构:
details
object不幸的是,我只能使用json_build_object
因为上面的结构已经定义了,所以不能更改。
谢谢!
她可以举一个例子来说明你能做什么。 您必须更正并完成此脚本,但我认为它可以完成这项工作
select json_build_object(b.name,json_build_object('details',row_to_json(b),
'floors',json_build_object('details',(select json_agg(row_to_json(f))->0 from (select * from floors f where f.building_id = b.id) f))))
from buildings b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.