我正尝试根据以下表构建JSON
table : car_makers
+------+-------------+---------+
| cmid | companyname | country |
+------+-------------+---------+
| 1 | Toyota | Japan |
| 2 | Volkswagen | Germany |
| 3 | Nissan | Japan |
+------+-------------+---------+
Table : cars
+------+---------+-----------+
| cmid | carname | cartype |
+------+---------+-----------+
| 1 | Camry | Sedan |
| 1 | Corolla | Sedan |
| 2 | Golf | Hatchback |
| 2 | Tiguan | SUV |
| 3 | Qashqai | SUV |
+------+---------+-----------+
我正在尝试创建以下结构的嵌套JSON:
{
"companyName": "Volkswagen",
"carType": "Germany",
"cars": {
"Tiguan": "SUV",
"Golf": "Hatchback"
}
}
但我对这个查询所能做的最好的
select json_build_object('companyName',companyName, 'carType', country, 'cars', JSON_AGG(json_build_object('carName', carName, 'carType', carType) ))
from car_makers cm
join cars c on c.cmid = cm.cmid
group by companyName,country
型
这是-
{
"companyName": "Volkswagen",
"carType": "Germany",
"cars": [
{
"carName": "Tiguan",
"carType": "SUV"
},
{
"carName": "Golf",
"carType": "Hatchback"
}
]
}
那么,我该如何修正当前的查询,用列值中的键-值对的json元素替换嵌套的json数组呢?
下面是fiddle,其中包含示例数据和我尝试过的查询
1条答案
按热度按时间bqf10yzr1#
您可以使用
json_object_agg
:See fiddle .