jsonb_array_elements 获取元素位置

dkn*_*ack 4 sql postgresql json

我有一个JSONB包含多行的列的表。每行包含一个JSON数组。

现在我需要将其放入行中,但我也需要元素的位置。

例如

select *
from (
   select jsonb_array_elements("values"::jsonb) from "myData"
) as x;
Run Code Online (Sandbox Code Playgroud)

给我所有行的所有数组中的所有元素。

我怎样才能获得数组索引?

data                        
----------------------------
{ text: "Hello" } | 0 <-- first array element from first row
{ text: "World" } | 1 <-- second array element from first row
{ text: "Hallo" } | 0 <-- first array element from second row
{ text: "Welt!" } | 1 <-- second array element from second row
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 5

使用横向连接和with ordinality

select *
from (
    select t.* 
    from "myData", jsonb_array_elements("values") with ordinality as t(data, idx)
) as x;
Run Code Online (Sandbox Code Playgroud)

如果"values"已经是一jsonb列,则无需将其强制转换为jsbon