简单的查询工作正常:
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
提前致谢!
最佳答案
使用函数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)
If the WITH ORDINALITY clause is specified, an additional column of type bigint will be added to the function result columns. This column numbers the rows of the function result set, starting from 1.
关于sql - 带有数组索引(键)的 PostgreSQL json_array_elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48312183/