【问题标题】:PostgreSQL JsonB query for object in JSON array based on object attributesPostgreSQL JsonB根据对象属性查询JSON数组中的对象
【发布时间】:2015-09-09 20:24:25
【问题描述】:

所以我已经在 StackOverflow 上看到了对这个问题的其他一些回复,但没有一个对我有用。

{
    "data": {
        "list": [
            {"id": "2ac5bf6f-bc4a-49e8-8f9f-bc518a839981", "type": "type1"},
            {"id": "d15ac090-11ce-4c0c-a05d-d4238f01e8b0", "type": "type3"},
            {"id": "b98958fa-87c4-4dcc-aa84-beaf2b32c5c0", "type": "type1"},
            {"id": "854f4d2a-f37c-42cb-9a1f-17a15454a314", "type": "type2"},
            {"id": "555816da-4547-4a82-9e7e-1e92515bd82b", "type": "type2"},
            {"id": "0f7f4ced-61c2-45da-b15c-0e12058f66a7", "type": "type4"}

        ]
    }
}

这个 Json 存储在一个名为“questions”的字段中,现在我想在这个表中查询列表中具有某个 id 的对象。所以说我有 id 555816da-4547-4a82-9e7e-1e92515bd82b,我想返回

{"id": "555816da-4547-4a82-9e7e-1e92515bd82b", "type": "type2"} 

我在互联网上看到的(主要是这里)没有奏效的解决方案在这里:

SELECT questions->'data'->'list' 
FROM assignments 
WHERE id='81asd6230-126d-4bc8-9745-c4333338115c' 
AND questions->'data'->'list' @> '[{"id":"854f4d2a-f37c-42cb-9a1f-17a15454a314"}]';

我已经在多个不同的响应中看到了这个解决方案,但它根本没有缩小数组的范围,它每次都返回完整的东西。 where 子句中的第一个 id 是我想要的特定分配对象的 id,在这里几乎无关紧要。

SELECT questions->'data'->'list' 
FROM assignments 
WHERE id='81asd6230-126d-4bc8-9745-c4333338115c' 
AND questions->'data'->'list' @> '[{"id":"854f4d2a-f37c-42cb-9a1f-17a15454a314"}]';

这不返回任何内容。

有没有人知道如何轻松做到这一点?

【问题讨论】:

    标签: sql json postgresql jsonb


    【解决方案1】:

    你可以使用函数jsonb_array_elements(jsonb)来选择一个json数组的所有元素:

    select jsonb_array_elements(questions->'data'->'list') elem
    from assignments
    where id='81asd6230-126d-4bc8-9745-c4333338115c'
    
                                  elem
    -----------------------------------------------------------------
     {"id": "2ac5bf6f-bc4a-49e8-8f9f-bc518a839981", "type": "type1"}
     {"id": "d15ac090-11ce-4c0c-a05d-d4238f01e8b0", "type": "type3"}
     {"id": "b98958fa-87c4-4dcc-aa84-beaf2b32c5c0", "type": "type1"}
     {"id": "854f4d2a-f37c-42cb-9a1f-17a15454a314", "type": "type2"}
     {"id": "555816da-4547-4a82-9e7e-1e92515bd82b", "type": "type2"}
     {"id": "0f7f4ced-61c2-45da-b15c-0e12058f66a7", "type": "type4"}
    (6 rows)
    

    如果要选择具有特定id 的元素,请使用上述查询:

    select elem
    from (
        select jsonb_array_elements(questions->'data'->'list') elem
        from assignments
        where id='81asd6230-126d-4bc8-9745-c4333338115c'
        ) sub
    where elem->>'id' = '854f4d2a-f37c-42cb-9a1f-17a15454a314'
    
                                  elem
    -----------------------------------------------------------------
     {"id": "854f4d2a-f37c-42cb-9a1f-17a15454a314", "type": "type2"}
    (1 row)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 2022-01-11
    • 2019-02-17
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    相关资源
    最近更新 更多