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

标签 sql arrays json postgresql

简单的查询工作正常:

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)

来自 the documentation:

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/

相关文章:

javascript - .map() 仅返回数组中的最后一个对象

php - 使用 Swift 3 XCode 8 解析 JSON

mysql - Hive 中的 SQL 查询获取 2 列中的前 2 个值

mysql - 加快 MySQL SUM + JOINS 的速度

javascript - 如何确定包含对象的两个数组之间的差异

javascript - for 循环迭代 array[i] 仅迭代到最后一个索引?

mysql - 是否可以在 mysql 中插入单词和变量的组合?

sql - 使用 string_to_array() 将 Oracle 转换为 PostgreSQL 查询

javascript - 多次读取数组会出现错误javascript

java - 如果值不是 Json 格式,则不反序列化值