Dav*_*ler 9 sql postgresql json
在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)
Run Code Online (Sandbox Code Playgroud)
JSON始终是包含可变数量哈希的数组.每个哈希都具有相同的密钥集.我正在尝试编写一个查询,该查询为JSON数组中的每个条目返回一行,每个哈希键的列和来自things表的id.我希望输出如下:
thing_id | json1 | json2
----------+-------+-------
1 | 123 | 456
1 | 124 | 457
2 | 234 | 567
Run Code Online (Sandbox Code Playgroud)
即两行用于JSON数组中具有两个项的条目.是否有可能让Postgres这样做?
json_populate_recordset感觉就像答案的一个重要部分,但我不能让它同时与多行一起工作.
Clo*_*eto 13
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5253 次 |
| 最近记录: |