我在postgres数据库中存储了一个json数组。json如下所示:
[
{
"operation": "U",
"taxCode": "1000",
"description": "iva description",
"tax": "12"
},
{
"operation": "U",
"taxCode": "1001",
"description": "iva description",
"tax": "12"
},
{
"operation": "U",
"taxCode": "1002",
"description": "iva description",
"tax": "12"
}
]现在,我需要对数组执行SELECT操作,以便任何元素都位于查询结果的不同行中。因此,我执行的SELECT语句必须以这种方式返回数据:
data
--------------------------------------------------------------------------------------
{ "operation": "U", "taxCode": "1000", "description": "iva description", "tax":"12"}
{ "operation": "U", "taxCode": "1001", "description": "iva description", "tax":"12"}
{ "operation": "U", "taxCode": "1002", "description": "iva description", "tax":"12"}我尝试使用unnest()函数
SELECT unnest(json_data::json)
FROM my_table但是它不接受jsonb类型。
发布于 2016-09-14 18:26:29
我把最初由pozs写的答案贴在评论区。
unnest()用于PostgreSQL的数组类型。
相反,可以使用以下函数之一:
json_array_elements(json) (9.3+)jsonb_array_elements(jsonb) (9.4+)json[b]_array_elements_text(json[b]) (9.4+)示例
select * from json_array_elements('[1,true, [2,false]]')输出值
-------------
| 1 |
-------------
| true |
-------------
| [2,false] |
-------------可以在其中找到v9.4文档的Here。
发布于 2018-04-10 01:41:46
更难的例子:
假设您有一个表,每个表中的行都包含jsonb数组,您希望拆分(或取消嵌套)所有这些数组,并对其中包含的记录执行一些聚合计算。
表(设为categories):
id | specifics (jsonb)
-----------------------------------------------------------------------------------
1 | [{"name": "Brand", "required": true}, {"name": "Color", "required": false}]
2 | [{"name": "Brand", "required": false}, {"name": "Color", "required": false}]所以,如果你想计算你有多少需要的细节,你将需要使用这样的查询:
SELECT specs.name, COUNT(*) AS total
FROM
categories,
jsonb_to_recordset(categories.specifics) AS specs(name jsonb, required boolean)
WHERE
specs.required = TRUE
-- AND any other restrictions you need
GROUP BY specs.name
ORDER BY total DESC;这里FROM x, function(x.column)是lateral join的缩写形式,它有效地将categories中的每一行与由jsonb_to_recordset函数从jsonb数组中创建的虚拟表连接在同一行中。
结果将是:
name | total
---------------
Brand | 1链接到数据库文件:https://www.db-fiddle.com/f/c4xZcEgg9dsPVDtE7Keovv/0
发布于 2016-05-26 02:34:06
我建议在您的情况下使用json_to_recordset命令。然后,您的SQL应为:
select *
from json_to_recordset('[{"operation":"U","taxCode":1000},{"operation":"U","taxCode":10001}]')
as x("operation" text, "taxCode" int);输出为:
------------------------
| |operation|taxCode |
------------------------
| 1 | "U" | 1000 |
------------------------
| 2 | "U" | 10001 |
------------------------示例中的列(或JSON键)可以自由地进一步扩展。
https://stackoverflow.com/questions/36174881
复制相似问题