How to get particular object from jsonb in PostgreSQL?

纵饮孤独 提交于 2019-12-11 03:07:24

问题


I have a table called 'Test' that holds two fields 'qnId' and 'Answers'. 'qnId' stores a uuid and 'Answers' is a jsonb array that roughly looks like this:

[{ "user" : "1", "ans" : "some text" }, { "user" : "3", "ans": "some text"}]

how can I retrieve the value of "ans" of "user" with value 3. How can I retrieve the value using normal SQL queries


回答1:


demo:db<>fiddle

You can use jsonb_array_elements() to expand the array elements into one row each. Afterwards you are able to filter the right elements using the ->> operator (documentation):

SELECT
    uuid,
    elements ->> 'ans'
FROM
    mytable,
    jsonb_array_elements(answers) elements
WHERE 
    elements ->> 'user' = '3'



回答2:


try something like this:

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'

same, but from 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'


来源:https://stackoverflow.com/questions/57339793/how-to-get-particular-object-from-jsonb-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!