PostgreSQL JsonB根据对象属性查询JSON数组中的对象

use*_*369 3 sql arrays postgresql json jsonb

我已经在 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"}

        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

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

{"id": "555816da-4547-4a82-9e7e-1e92515bd82b", "type": "type2"} 
Run Code Online (Sandbox Code Playgroud)

我在互联网上看到的解决方案(主要是在这里),但没有起作用,如下:

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

我已经在多个不同的响应中看到了这个解决方案,但它根本没有缩小数组范围,它每次都返回完整的内容。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"}]';
Run Code Online (Sandbox Code Playgroud)

这不会返回任何内容。

有谁知道如何轻松地做到这一点?

kli*_*lin 5

您可以使用函数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)
Run Code Online (Sandbox Code Playgroud)

如果您想选择具有特定属性的元素,请使用上面的查询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)
Run Code Online (Sandbox Code Playgroud)