[英]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.