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

时间:2018-03-21 08:37:14

标签: sql json postgresql

我有一个表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
        }

有人可以帮助我如何使用 PostgreSql 从给定的option options中选择id个对象?

1 个答案:

答案 0 :(得分:0)

你可以选择它。 unnest并过滤,例如:

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)