使用json对象数组创建一个json对象

时间:2016-10-13 18:59:38

标签: json postgresql

在postgres中说我有这样的架构:

table item {
    type varchar(40)
    entity_id bigint
    entity_type varchar(40)
    user_id   bigint
}

我想查询表格以获取如下信息:

{
    "typeA": {
        "count": 3,
        "me": true
    },
    "typeC": {
        "count": 3,
        "me": false
    },
    "typeE": {
        "count": 3,
        "me": false
    },
    "typeR": {
        "count": 3,
        "me": true
    }
}

来自主数据为的查询:

SELECT ARRAY_AGG(x)
    FROM
    (
        SELECT type,
        count(*),
        (CASE
            WHEN (SELECT id
                FROM items as i
                WHERE i.entity_type = 'sometype'
                    AND i.entity_id = 234
                    AND i.user_id = 32
                    AND i.type = items.type) is not null
            THEN true
            ELSE false
        END) AS me
        FROM items
        WHERE  items.entity_type = 'sometype'
        AND items.entity_id = 234
        GROUP BY type
    ) as x

这将返回我需要类型计数和我的信息数组。但我需要格式化如上:

[
    {
        "type": "typeA",
        "count": 3,
        "me": true
    },
    {
        "type": "typeC",
        "count": 3,
        "me": false
    },
    {
        "type": "typeE",
        "count": 3,
        "me": false
    },
    {
        "type": "typeR",
        "count": 3,
        "me": true
    }
]

格式化的当前方式是什么。一直无法找到构建我需要的json对象的方法。我能够得到三个类似的json对象但是我需要将三个嵌套在一个对象中。

1 个答案:

答案 0 :(得分:0)

不完全是您想要的,但我想,PostgreSQL - Aggregate Functions,您可以尝试json_object_agg(name, value),例如。

SELECT JSON_OBJECT_AGG(type, x)
    FROM
    (
        SELECT type,
        count(*),
        (CASE
            WHEN (SELECT id
                FROM items as i
                WHERE i.entity_type = 'sometype'
                    AND i.entity_id = 234
                    AND i.user_id = 32
                    AND i.type = items.type) is not null
            THEN true
            ELSE false
        END) AS me
        FROM items
        WHERE  items.entity_type = 'sometype'
        AND items.entity_id = 234
        GROUP BY type, me
    ) as x