[英]PostgreSQL JSON Query with embedded json Object
我是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
您可以在子查詢中包裝對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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.