带有数组索引(键)的 PostgreSQL json_array_elements

Eug*_*nyi 1 sql postgresql json function

简单查询工作正常:

SELECT json_array_elements_text('["first", "third", "second"]'::json)
Run Code Online (Sandbox Code Playgroud)

但我也想以某种方式检索数组键,因此输出如下:

key    value
 0     first
 1     third
 2     second
Run Code Online (Sandbox Code Playgroud)

UPD

好像 row_number() 是 ap?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"]
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

提前致谢!

kli*_*lin 6

使用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)
Run Code Online (Sandbox Code Playgroud)

文档:

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