遍历 JSON 数组中的每个元素并与行连接

Iterate over each element in JSON array and join with rows

我正在尝试编写一个 SQL 查询,将每一行与其自己的 JSON 数组元素交叉连接。 假设这是我们拥有的数据(我知道,这没有多大意义):

| id | name | info                                            |
|----|------|-------------------------------------------------|
| 1  | john | [{score: 20, point: 10},{score: 25, point: 15}] |
| 2  | jane | [{score: 25, point: 15},{score: 35, point: 45}] |

我想要得到的最终结果是这样的:

| id | name | score | point |
|----|------|-------|-------|
| 1  | john | 20    | 10    |
| 1  | john | 25    | 15    |
| 2  | jane | 25    | 15    |
| 2  | jane | 35    | 45    |

我如何编写完成这项工作的查询?我没有创建新函数的授权,所以这必须是纯粹的 select 语句,而不是 plpgsql 东西。

您可以使用横向连接取消嵌套 json[b]_array_elements:

select t.id, t.name, i.obj ->> 'score' as score, i.obj ->> 'point' as point
from mytable t
cross join lateral jsonb_array_elements(t.info) i(info)