如何从 PostgreSQL 中的 jsonb 获取特定对象?
How to get particular object from jsonb in PostgreSQL?
我有一个名为 'Test' 的 table,它包含两个字段 'qnId' 和 'Answers'。
'qnId'存储一个uuid,'Answers'是一个jsonb数组,大致长这样:
[{ "user" : "1", "ans" : "some text" }, { "user" : "3", "ans": "some text"}]
如何检索 "user"
的 "ans"
的值为 3
。
如何使用普通 SQL 查询
检索值
尝试这样的事情:
select
x ->> 'ans' as user_3_ans
from
jsonb_array_elements('[{ "user" : "1", "ans" : "some text 1" }, { "user" : "3", "ans": "some text 3"}]'::jsonb) as x
where
x ->> 'user' = '3'
相同,但来自 table:
with
table1 as (
select
1 as id,
'[{ "user" : "1", "ans" : "some text 1" }, { "user" : "3", "ans": "some text 3"}]'::jsonb as answers
)
select
id,
answers,
el ->> 'ans' as user_3_ans
from
( select
id,
answers,
jsonb_array_elements(answers) as el
from
table1) as x
where
el ->> 'user' = '3'
您可以使用jsonb_array_elements()
将数组元素扩展为一行。之后,您可以使用 ->>
运算符 (documentation):
过滤正确的元素
SELECT
uuid,
elements ->> 'ans'
FROM
mytable,
jsonb_array_elements(answers) elements
WHERE
elements ->> 'user' = '3'
我有一个名为 'Test' 的 table,它包含两个字段 'qnId' 和 'Answers'。 'qnId'存储一个uuid,'Answers'是一个jsonb数组,大致长这样:
[{ "user" : "1", "ans" : "some text" }, { "user" : "3", "ans": "some text"}]
如何检索 "user"
的 "ans"
的值为 3
。
如何使用普通 SQL 查询
尝试这样的事情:
select
x ->> 'ans' as user_3_ans
from
jsonb_array_elements('[{ "user" : "1", "ans" : "some text 1" }, { "user" : "3", "ans": "some text 3"}]'::jsonb) as x
where
x ->> 'user' = '3'
相同,但来自 table:
with
table1 as (
select
1 as id,
'[{ "user" : "1", "ans" : "some text 1" }, { "user" : "3", "ans": "some text 3"}]'::jsonb as answers
)
select
id,
answers,
el ->> 'ans' as user_3_ans
from
( select
id,
answers,
jsonb_array_elements(answers) as el
from
table1) as x
where
el ->> 'user' = '3'
您可以使用jsonb_array_elements()
将数组元素扩展为一行。之后,您可以使用 ->>
运算符 (documentation):
SELECT
uuid,
elements ->> 'ans'
FROM
mytable,
jsonb_array_elements(answers) elements
WHERE
elements ->> 'user' = '3'