Postgres多对多JSON聚合

时间:2016-08-25 01:02:30

标签: json postgresql nested

过去几天我一直在努力查询,我希望有人可以提供帮助。我有3张桌子:

CREATE TABLE user (
    ID SERIAL PRIMARY KEY,
    USERNAME TEXT NOT NULL UNIQUE
);

CREATE TABLE skill (
    ID SERIAL PRIMARY KEY,
    NAME TEXT NOT NULL
);

CREATE TABLE user_skill (
    ID SERIAL PRIMARY KEY,
    USER_ID INTEGER REFERENCES user(id),
    SKILL_ID INTEGER REFERENCES skill(id)
);

我正在尝试运行一个查询,以便我可以返回一个具有JSON格式的单个对象,如下所示:

{
    "id": 1,
    "username": "test123",
    "skills": [{
        "name": "skillOne"
    }, {
        "name": "skillTwo"
    }, {
        "name": "skillThree"
    }]
}

到目前为止我的样子是这样的:

SELECT
    json_build_object(
        'id', u.id,
        'username', u.username,
        'skills', jsonb_agg(skill)
    )  
FROM (
    SELECT 
        jsonb_build_object(
            'name', s.name
        ) skill
    FROM user_skill us
    JOIN skill s ON us.skill_id = s.id
) xombi_user u;

编辑:

我现在有了这个正确返回json数组,但现在需要构建一个json对象。

SELECT u.id, u.username, jsonb_agg(s)
    FROM user u
    LEFT JOIN user_skill us ON u.id = us.user_id
    LEFT JOIN skill s ON us.skill_id = s.id
    WHERE u.id = 60
GROUP BY u.id;

1 个答案:

答案 0 :(得分:0)

知道了!希望它可以帮助某人:

SELECT 
    json_build_object(
        'id', u.id,
        'username', u.username,
        'skills', jsonb_agg(s)
    ) 
    FROM user u
    LEFT JOIN user_skill us ON u.id = us.user_id
    LEFT JOIN skill s ON us.skill_id = s.id
    WHERE u.id = 60
GROUP BY u.id;