我已经对此进行了很多搜索,但仍然无法回答。我正在使用PostgreSQL。在下面的示例中,列名称为“ sections”,列类型为json []。
我的专栏在数据库中看起来像这样:
sections
[{"name" : "section1",
"attributes": [{"attrkey1": "value1",
"attrkey2": "value2"},
{"attrkey3": "value3",
"attrkey4": "value4"}]
},
{"name" : "section2",
"attributes": [{"attrkey3": "value5",
"attrkey6": "value6"},
{"attrkey1": "value7",
"attrkey8": "value8"}]
}]
这是json数组,我想在结果中获取“ attrkey3”。为了从Json获得特定的密钥,我可以使用json_extract_path_text(json_column, 'json_property')
它,它工作得很好。但是我不知道如何从json []获取一些属性。
如果我谈论上面的示例,我想获取属性“ attrkey2”的值以在结果中显示。我知道这是一个数组,因此它的工作方式可能与平时不同,例如,数组的所有值都将充当不同的行,因此我可能不得不编写子查询,但不知道如何执行。
另外,我不能静态地编写索引,也不能从某个特定索引获取json元素的属性。我的查询将动态生成,因此我永远不会知道json数组中有多少个元素。
我看到了一些静态示例,但不知道如何实现。有人可以告诉我如何在查询中执行此操作吗?
我不确定您是否具有json[]
(PostgreSQLjson
值数组)类型化的列或json
类型化的列,它似乎是一个JSON数组(如您的示例)。
无论哪种情况,都需要在查询之前扩展数组。在情况下json[]
,你需要使用的unnest(anyarray)
; 对于json
类型列中的JSON数组,您需要使用json_array_elements(json)
(和LATERAL
连接-它们在我的示例中是隐式的):
select t.id,
each_section ->> 'name' section_name,
each_attribute ->> 'attrkey3' attrkey3
from t
cross join unnest(array_of_json) each_section
cross join json_array_elements(each_section -> 'attributes') each_attribute
where (each_attribute -> 'attrkey3') is not null;
-- use "where each_attribute ? 'attrkey3'" in case of jsonb
select t.id,
each_section ->> 'name' section_name,
each_attribute ->> 'attrkey3' attrkey3
from t
cross join json_array_elements(json_array) each_section
cross join json_array_elements(each_section -> 'attributes') each_attribute
where (each_attribute -> 'attrkey3') is not null;
不幸的是,您不能对数据使用任何索引。为此,您需要先修复架构。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句