如何在 JSONB 类型列中重新排序数组

问题描述 投票:0回答:1

在 PostgreSQL 表中,一个 JSONB 类型的列,里面存储的值是一个数组

[3,6,78,1]

我该怎么做才能像

[1,3,6,78]
那样重新排序?

arrays json postgresql aggregate-functions jsonb
1个回答
4
投票

使用

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($1) 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)
© www.soinside.com 2019 - 2024. All rights reserved.