简体   繁体   中英

object of objects query using postgresql

i am using postgresql

in profile model there is field (progress ) which is an object and inside this object there are multiple objects

each object has 2 number

i want to check if those 2 numbers are equal to do increase points

progress : {
    "progress1": {
        "mustWin": 1,
        "progress": 0
    },
    "progress2": {
        "mustWin": 1,
        "progress": 0
    },
}

this is the default value of progress

how can i get access to progress1 and 2

If you want to manually gets progress1 and progress2 values, then use this:

with tb as (
select 
'{"progress" : {
    "progress1": {
        "mustWin": 1,
        "progress": 0
    },
    "progress2": {
        "mustWin": 1,
        "progress": 0
    } 
}}'::jsonb as js 
)
select 
    tb.js->'progress'->'progress1', 
    tb.js->'progress'->'progress2'  
from tb 

-- Result:
|progress1                    |progress2                    |
|-----------------------------+-----------------------------+
|{"mustWin": 1, "progress": 0}|{"mustWin": 1, "progress": 0}|

If you don't know how many objects have inside progress, then use this:

with tb as (
select 
'{"progress" : {
    "progress1": {
        "mustWin": 1,
        "progress": 0
    },
    "progress2": {
        "mustWin": 1,
        "progress": 0
    }, 
    "progress3": {
        "mustWin": 1,
        "progress": 0
    }, 
    "progress4": {
        "mustWin": 1,
        "progress": 0
    } 
}}'::jsonb as js 
)
select tb2."key", tb2."value" from tb tb1 
cross join jsonb_each_text(tb1.js->'progress') tb2  

-- Result:
| key       | value                         |
|-----------|-------------------------------|
| progress1 | {"mustWin": 1, "progress": 0} |
| progress2 | {"mustWin": 1, "progress": 0} |
| progress3 | {"mustWin": 1, "progress": 0} |
| progress4 | {"mustWin": 1, "progress": 0} |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM