PostgreSQL json_array_elements与数组索引(键)

时间:2018-01-18 00:38:14

标签: sql json postgresql function

简单查询工作正常:

SELECT json_array_elements_text('["first", "third", "second"]'::json)

但是我也想以某种方式检索数组键,所以输出就像:

key    value
 0     first
 1     third
 2     second

UPD

看起来像row_number()是一个p̶r̶o̶p̶e̶r̶解决方案,但我无法弄清楚如何进一步使用它。

假设我有'帖子'表,每个帖子都包含一系列JSON格式的相关评论:

SELECT id, title, comments FROM posts

id     title             comments
 1    Title 1  ["comment 1", "comment 2"]
 2    Title 2  ["comment 3", "comment 4", "comment 5"]
 3    Title 3  ["comment 6"]

目标是不仅扩展评论值,还扩展键:

Tricky SQL here

id     title    comment   key
 1    Title 1  comment 1   0
 1    Title 1  comment 2   1
 2    Title 2  comment 3   0
 2    Title 2  comment 4   1
 2    Title 2  comment 5   2
 3    Title 3  comment 6   0

UPD2

使用row_numbers()的解决方案:

SELECT *, row_number() OVER (PARTITION BY id) - 1 AS key
FROM (
  SELECT id, title, json_array_elements_text(comments::json) AS comment
  FROM posts
) p

提前致谢!

2 个答案:

答案 0 :(得分:3)

将函数json_array_elements_text()与常规:

一起使用
with my_table(id, title, comments) as (
values
(1, 'Title 1', '["comment 1", "comment 2"]'::json),
(2, 'Title 2', '["comment 3", "comment 4", "comment 5"]'),
(3, 'Title 3', '["comment 6"]')
)

select id, title, value as comment, ordinality- 1 as key
from my_table
cross join json_array_elements_text(comments) with ordinality

 id |  title  |  comment  | key 
----+---------+-----------+-----
  1 | Title 1 | comment 1 |   0
  1 | Title 1 | comment 2 |   1
  2 | Title 2 | comment 3 |   0
  2 | Title 2 | comment 4 |   1
  2 | Title 2 | comment 5 |   2
  3 | Title 3 | comment 6 |   0
(6 rows)

来自the documentation:

  

如果指定了WITH ORDINALITY子句​​,则会在函数结果列中添加bigint类型的附加列。此列从1开始对函数结果集的行进行编号。

答案 1 :(得分:0)

JSON数组没有键,但是您可以使用rownum:

获得所需的输出
SELECT row_number() OVER ()-1 AS key, *
FROM json_array_elements_text('["first", "third", "second"]'::json) q

sqlfiddle