簡體   English   中英

Postgres:將 JSON 列展開為行

[英]Postgres: Expand JSON column into rows

在 Postgres 9.3 數據庫中,我有一個表,其中一列包含 JSON,如下例所示的測試表所示。

test=# create table things (id serial PRIMARY KEY, details json, other_field text);
CREATE TABLE
test=# \d things
                            Table "public.things"
   Column    |  Type   |                      Modifiers
-------------+---------+-----------------------------------------------------
 id          | integer | not null default nextval('things_id_seq'::regclass)
 details     | json    |
 other_field | text    |
Indexes:
    "things_pkey" PRIMARY KEY, btree (id)

test=# insert into things (details, other_field) 
       values ('[{"json1": 123, "json2": 456},{"json1": 124, "json2": 457}]', 'nonsense');
INSERT 0 1
test=# insert into things (details, other_field) 
       values ('[{"json1": 234, "json2": 567}]', 'piffle');
INSERT 0 1
test=# select * from things;
 id |                           details                           | other_field
----+-------------------------------------------------------------+-------------
  1 | [{"json1": 123, "json2": 456},{"json1": 124, "json2": 457}] | nonsense
  2 | [{"json1": 234, "json2": 567}]                              | piffle
(2 rows)

JSON 始終是一個包含可變數量哈希的數組。 每個散列始終具有相同的鍵集。 我正在嘗試編寫一個查詢,它為 JSON 數組中的每個條目返回一行,每個哈希鍵的列和 things 表中的 id。 我希望輸出如下:

 thing_id | json1 | json2
----------+-------+-------
        1 |   123 |   456
        1 |   124 |   457
        2 |   234 |   567

即 JSON 數組中包含兩個項目的條目的兩行。 是否有可能讓 Postgres 做到這一點? json_populate_recordset感覺像是答案的重要組成部分,但我不能讓它一次處理超過一行。

select id,
    (details ->> 'json1')::int as json1,
    (details ->> 'json2')::int as json2
from (
    select id, json_array_elements(details) as details
    from things
) s
;
 id | json1 | json2 
----+-------+-------
  1 |   123 |   456
  1 |   124 |   457
  2 |   234 |   567

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM