给定一个对象数组,我们可以很容易地用 jsonb_to_recordset 把它变成记录集。
select * from jsonb_to_recordset($$[
{"name": "name01", "age": 12},
{"name": "name02", "age": 14},
{"name": "name03", "age": 16},
{"name": "name04", "age": 18}
]$$) as (name text, age int)
name |age |
-------|----|
name01 |12 |
name02 |14 |
name03 |16 |
name04 |18 |
但是,如果我们更喜欢 array of array 形式的源数据,我们该怎么办?如何转换以下查询以产生与上述类似的结果?
select array['name', 'age'] "labels"
, x.value "values"
from jsonb_array_elements($$[
["name01", 12],
["name02", 14],
["name03", 16],
["name04", 18]
]$$) x
labels |values |
-----------|---------------|
{name,age} |["name01", 12] |
{name,age} |["name02", 14] |
{name,age} |["name03", 16] |
{name,age} |["name04", 18] |