繁体   English   中英

带有嵌入式json对象的PostgreSQL JSON查询

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM