我是postgres的新手,我无法找到如何查询以下内容的示例:
{
"Skill": {
"Technical": [
{ "Name": "C#",
"Rating": 4,
"Last Used": "2014-08-21"
},
{ "Name": "ruby",
"Rating": 4,
"Last Used": "2014-08-21"
}
],
"Product": [
{ "Name": "MDM",
"Rating": 4,
"Last Used": "2014-08-21"
},
{ "Name": "UDM",
"Rating": 5,
"Last Used": "2014-08-21"
}
]
}
}
简而言之,我一直在努力理解如何通过地图查询,而不必明确命名每个键。
我有一个查询执行以下操作,但似乎有点太多了...
Select 'Technical' as SkillType
, json_array_elements(ResourceDocument->'Skill'->'Technical')->>'Name' as SkillName
, json_array_elements(ResourceDocument->'Skill'->'Technical')->>'Rating' as Rating
, json_array_elements(ResourceDocument->'Skill'->'Technical')->>'Last Used' as LastUsed
FROM testdepot.Resource
UNION ALL
Select 'Product' as SkillType
, json_array_elements(ResourceDocument->'Skill'->'Product')->>'Name' as SkillName
, json_array_elements(ResourceDocument->'Skill'->'Product')->>'Rating' as Rating
, json_array_elements(ResourceDocument->'Skill'->'Product')->>'Last Used' as LastUsed
FROM testdepot.Resource
我试图在1个查询中找到一种方法来执行此操作,该查询允许包含地图的所有键。 在这种情况下产品和技术 类似的东西:
Select 'Product' as SkillType
, json_array_elements(ResourceDocument->'Skill'->*)->>'Name' as SkillName
, json_array_elements(ResourceDocument->'Skill'->*)->>'Rating' as Rating
, json_array_elements(ResourceDocument->'Skill'->*)->>'Last Used' as LastUsed
FROM testdepot.Resource
答案 0 :(得分:0)
您可以在子查询中包含对json_object_keys
的调用,以首先获取"Skill"
中的键,然后对结果使用外部查询json_array_elements
:
SELECT SkillType
, json_array_elements(ResourceDocument->'Skill'->SkillType)->>'Name' AS SkillName
, json_array_elements(ResourceDocument->'Skill'->SkillType)->>'Rating' AS Rating
, json_array_elements(ResourceDocument->'Skill'->SkillType)->>'Last Used' AS LastUsed
FROM (
SELECT json_object_keys(resourcedocument->'Skill') AS SkillType, ResourceDocument
FROM Resource
) t;