如何在 JSONB 类型列中重新排序数组
How to reorder array in JSONB type column
在PostgreSQL中table,一个JSONB类型的列,里面存储的值是一个数组[3,6,78,1]
。
我应该怎么做才能像[1,3,6,78]
一样重新排序?
使用 jsonb_array_elements()
解除数组嵌套并使用 jsonb_agg()
:
聚合其排序元素
with the_data(val) as (values ('[3,6,78,1]'::jsonb))
select jsonb_agg(elem order by elem) as val
from the_data
cross join lateral jsonb_array_elements(val) as arr(elem);
val
---------------
[1, 3, 6, 78]
(1 row)
您可以在自定义函数中使用查询,这在更复杂的查询中会很方便:
create or replace function jsonb_sort_array(jsonb)
returns jsonb language sql immutable
as $$
select jsonb_agg(elem order by elem)
from jsonb_array_elements() as arr(elem)
$$;
with the_data(val) as (values ('[3,6,78,1]'::jsonb))
select jsonb_sort_array(val) as val
from the_data;
val
---------------
[1, 3, 6, 78]
(1 row)
在PostgreSQL中table,一个JSONB类型的列,里面存储的值是一个数组[3,6,78,1]
。
我应该怎么做才能像[1,3,6,78]
一样重新排序?
使用 jsonb_array_elements()
解除数组嵌套并使用 jsonb_agg()
:
with the_data(val) as (values ('[3,6,78,1]'::jsonb))
select jsonb_agg(elem order by elem) as val
from the_data
cross join lateral jsonb_array_elements(val) as arr(elem);
val
---------------
[1, 3, 6, 78]
(1 row)
您可以在自定义函数中使用查询,这在更复杂的查询中会很方便:
create or replace function jsonb_sort_array(jsonb)
returns jsonb language sql immutable
as $$
select jsonb_agg(elem order by elem)
from jsonb_array_elements() as arr(elem)
$$;
with the_data(val) as (values ('[3,6,78,1]'::jsonb))
select jsonb_sort_array(val) as val
from the_data;
val
---------------
[1, 3, 6, 78]
(1 row)