2016-02-09 98 views
2

我需要編寫SQL代碼,即INSERT到一些表數據中,那個表存儲在另一個表中作爲JSON。 PostgreSQL 9.5。Json列用數組來記錄

我有一張名爲的評論。它有一個JSON科拉姆裁判像這樣的數據:

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

正如你所看到的,有可能在JSON多個項目(對)。

我需要編寫SQL代碼,將採取從評論其中裁判 IS NOT NULL的所有記錄,並插入到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

使用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)  
+0

什麼是'ref'呢? –

+0

json專欄;應該是'refs'。 – klin