postgresql 正在将数组的数组与postgres合并

hc2pp10m  于 2023-03-12  发布在  PostgreSQL
关注(0)|答案(2)|浏览(194)

我有下面的jsonb:

[
    [
        {
            "id": 51003,
            "user_id": 4554,
            "sg_id": 143353
        }, {
            "id": 51004,
            "user_id": 4555,
            "sg_id": 143353
        }
    ],
    [
        {
            "id": 51005,
            "user_id": 4555,
            "sg_id": 143354
        }
    ]
]

我尝试通过删除嵌套的数组级别来减少它。我期望类似这样的结果:

[
    {
        "id": 51003,
        "user_id": 4554,
        "sg_id": 143353
    }, {
        "id": 51004,
        "user_id": 4555,
        "sg_id": 143353
    }, {
        "id": 51005,
        "user_id": 4555,
        "sg_id": 143354
    }
]

我不知道如何解决与postgres,并将感谢任何帮助。干杯!

tp5buhyn

tp5buhyn1#

WITH j_array AS (
    SELECT
        a || lag(a) OVER () AS b
    FROM
        jsonb_array_elements('[
    [
        {
            "id": 51003,
            "user_id": 4554,
            "sg_id": 143353
        }, {
            "id": 51004,
            "user_id": 4555,
            "sg_id": 143353
        }
    ],
    [
        {
            "id": 51005,
            "user_id": 4555,
            "sg_id": 143354
        }
    ]
]'::jsonb) AS j (a))
SELECT
    *
FROM
    j_array
WHERE
    b IS NOT NULL;

 b                                                                          
-----------------------------------------------------------------------------------------------------------------------------------------------------
 [{"id": 51005, "sg_id": 143354, "user_id": 4555}, {"id": 51003, "sg_id": 143353, "user_id": 4554}, {"id": 51004, "sg_id": 143353, "user_id": 4555}]
idfiyjo8

idfiyjo82#

->0以访问包含两个对象的数组的第一元素,||将最后一个数组的对象连接到数组中。
::jsonb就是把varchar转换成json

select myjson::jsonb->0 || to_jsonb(myjson::jsonb->1->0) as result
from mytable;

结果:

result

[{"id": 51003, "sg_id": 143353, "user_id": 4554}, {"id": 51004, "sg_id": 143353, "user_id": 4555}, {"id": 51005, "sg_id": 143354, "user_id": 4555}]

Demo here

相关问题