繁体   English   中英

从Postgres中的对象数组中选择对象

[英]Select object from array of objects in Postgres

我有一个表questions ,其中optionsjsonb ,它是一个对象数组。

"questions": [
        {
            "id": 76,
            "text": "What is the capital of Telangana ?",
            "options": [
                {
                    "id": 1,
                    "text": "Hyderabad",
                    "correct": true
                },
                {
                    "id": 2,
                    "text": "Bangalore",
                    "correct": false
                },
                {
                    "id": 3,
                    "text": "Amaravathi",
                    "correct": false
                },
                {
                    "id": 4,
                    "text": "Chennai",
                    "correct": false
                }
            ],
            "position": 1
        }

谁能帮我怎么能选择一个option从对象options由给定的id使用PostgreSQL?

您可以选择它。 嵌套和过滤,例如:

t=# with c(j) as (values('{"options": [
                {
                    "id": 1,
                    "text": "Hyderabad",
                    "correct": true
                },
                {
                    "id": 2,
                    "text": "Bangalore",
                    "correct": false
                },
                {
                    "id": 3,
                    "text": "Amaravathi",
                    "correct": false
                },
                {
                    "id": 4,
                    "text": "Chennai",
                    "correct": false
                }
            ]}'::jsonb))
, m as (select jsonb_array_elements(j->'options') a from c) select a from m where a->>'id' = '3';
                         a
---------------------------------------------------
 {"id": 3, "text": "Amaravathi", "correct": false}
(1 row)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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