postgresql 使用列值作为键值对创建嵌套json

pqwbnv8z  于 2022-12-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(218)

我正尝试根据以下表构建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,其中包含示例数据和我尝试过的查询

bqf10yzr

bqf10yzr1#

您可以使用json_object_agg

select json_build_object('companyName', c.companyName, 
   'country', c.country, 'cars', json_object_agg(c1.carName, c1.carType)) 
from car_makers c join cars c1 on c.cmid = c1.cmid
group by c.companyName, c.country

See fiddle .

相关问题