Json列与数组记录

时间:2016-02-09 08:25:40

标签: sql json postgresql

我需要编写SQL代码,将INSERT写入一些表数据,这些表存储在另一个表中作为JSON。 PostgreSQL 9.5。

我有一个名为评论的表格。它有一个JSON colum refs ,其数据如下:

[{"author":"John","tags":["ruby","rails"]}, {"author":"Nick","tags":["sql"]}]

如您所见,JSON中可能有多个项目(对)。

我需要编写SQL代码,它将从 comments 获取所有记录,其中 refs IS NOT NULL并且INSERT INTO comments_refs (不要问为什么我需要它:)),看起来像:

id                | integer                | not null default nextval(...)
comment_id        | integer                | not null
author            | character varying(255) | not null
tags              | text[]                 | not null default '{}'::text[]

我尝试使用json_to_recordset,但它不适用于数组(请参阅http://postgresql.nabble.com/bug-in-json-to-record-with-arrays-td5828415.html)。接下来,我尝试类似:

SELECT json_array_elements(rec.refs) FROM comments AS rec;

但是我没有想出怎么做..也许有人可以帮助我。感谢。

1 个答案:

答案 0 :(得分:1)

使用json_array_elements()

select comment_id, author, array_agg(tag) tags
from (
    select comment_id, e->>'author' author, e->'tags' tags
    from comments, json_array_elements(refs) e
    ) s,
    json_array_elements_text(tags) tag
group by 1, 2;

 comment_id | author |     tags     
------------+--------+--------------
          1 | John   | {ruby,rails}
          1 | Nick   | {sql}
(2 rows)