Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL:行到json()内部连接问题_Postgresql - Fatal编程技术网

PostgreSQL:行到json()内部连接问题

PostgreSQL:行到json()内部连接问题,postgresql,Postgresql,我有两个表:产品类别和产品 产品类别 +----+-------------+ |id |分类| +----+-------------+ |0 |电子| +----+-------------+ |1 |玩具| +----+-------------+ 产品 +----+-----------+-------+--------+ |id |名称|价格|参考id| +----+-----------+-------+--------+ |0 |耳机| 100 | 0| +----+-------

我有两个表:
产品类别
产品

产品类别
+----+-------------+
|id |分类|
+----+-------------+
|0 |电子|
+----+-------------+
|1 |玩具|
+----+-------------+
产品
+----+-----------+-------+--------+
|id |名称|价格|参考id|
+----+-----------+-------+--------+
|0 |耳机| 100 | 0|
+----+-----------+-------+--------+
|1 |电话| 200 | 0|
+----+-----------+-------+--------+
如何使用row_to_json()生成以下json字符串:

{
“分类”:“电子学”,
“产品”:[
{
“名称”:“耳机”,
“价格”:100
},
{
“姓名”:“电话”,
“价格”:200
}
]
}

您无法通过
行到行json
函数构建此嵌套的预期嵌套json文档。但这并不难:

select json_build_object('category', c.category, 
                         'products', json_agg(json_build_object('name', name, 
                                                                'price', price))) 
 from products 
      join product_category c 
      on ref_id = c.id 
group by c.category;
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                   json_build_object                                                   │
╞═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╡
│ {"category" : "electronics", "products" : [{"name" : "headphone", "price" : 100}, {"name" : "phone", "price" : 200}]} │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
(1 row)