从jsonb字段数组中获取数据

时间:2018-03-05 12:38:33

标签: sql postgresql jsonb

我在PostgreSQL数据库中有以下架构:

CREATE TABLE survey_results (
    id integer NOT NULL,
    raw jsonb DEFAULT '{}'::jsonb,
    created_at timestamp without time zone,
    updated_at timestamp without time zone  
);

INSERT INTO survey_results (id, raw, created_at, updated_at)
    VALUES (1, '{ "slides": [{"id": "1", "name": "Test", "finished_at": 1517421628092}, {"id": "2", "name": "Test", "finished_at": 1517421894736}]}', now(), now());

我想从raw['slides']获取数据。我希望查询返回每raw['slides'] idraw['slides'] finished_at。因此查询的结果应如下所示:

id  finished_at
1 1517421628092
2 1517421894736

这是sqlfiddle试验:

http://sqlfiddle.com/#!17/ae504

我如何在PostgreSQL中执行此操作?

1 个答案:

答案 0 :(得分:1)

您需要取消该阵列,然后您可以访问每个元素:

select s.slide ->> 'id' as id,
       s.slide ->> 'finished_at' as finished_at
from survey_results, jsonb_array_elements(raw -> 'slides') as s (slide)

http://sqlfiddle.com/#!17/ae504/80

有关详细信息,请参阅手册中的JSON Functions and Operators