如何在postgres中订购json列

时间:2019-10-09 06:00:40

标签: sql json postgresql

所以我有一个具有以下结构的jsonb列:

{
    "fields": [{
         "name": "John",
         "position": 1
    },{
         "name": "Mike",
         "position": 2
   }]
}

jsonb列在我的“人”表中。我想选择人员表,包括jsonb列,但我也希望jsonb列按“位置”降序排列,这有可能吗?

到目前为止,我有这个查询。

SELECT
    person_id
    name
    jsonb_agg(field ORDER BY field->'fields'->0->>'position' DESC)
FROM
    person
WHERE (
    person_id = 42
) GROUP BY name

1 个答案:

答案 0 :(得分:0)

假设表person具有以下结构和数据:

CREATE TABLE person (person_id, name, field) AS
VALUES
    (
        42,
        'foo',
        '{
            "fields": [
                { "name": "John", "position": 1 },
                { "name": "Mike", "position": 2 }
            ]
        }'::jsonb
    ),
    (
        13,
        'bar',
        '{
            "fields": [
                { "name": "Anne", "position": 33 },
                { "name": "Melinda", "position": 66 }
            ]
        }'::jsonb
    );

首先,必须将数组元素作为单独的行来进行排序(内部查询data)。然后,您必须重构JSON对象:

SELECT
    person_id,
    name,
    jsonb_build_object(
        'fields',
        jsonb_agg(element ORDER BY element->'position' DESC)
    )
FROM (
    SELECT
        person_id,
        name,
        jsonb_array_elements(field->'fields') AS element
    FROM person
) data
WHERE person_id = 42
GROUP BY
    person_id,
    name;

这将产生:

 person_id | name |                               jsonb_build_object
-----------+------+--------------------------------------------------------------------------------
        42 | foo  | {"fields": [{"name": "Mike", "position": 2}, {"name": "John", "position": 1}]}