gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:44:26 33 4
gpt4 key购买 nike

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

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

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"}]';

这不会返回任何内容。

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

最佳答案

您可以使用函数 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)

关于sql - PostgreSQL JsonB 根据对象属性查询 JSON 数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32488525/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com