PostgreSQL数组在JSON对象中

时间:2016-09-18 16:00:57

标签: sql json postgresql

我试图在PostgreSQL函数中使用左连接的两个表来构建自定义json,但它无法正常工作。

表格结构:

发表

 id | title | description

postPhoto

 id | postId (FK) | name 

json示例:

{
    postId: 1,
    title: ''
    description: '',
    postPhotos: [
        {id: 1, name: 'photo1.png'},
        {id: 1, name: 'photo2.png'},
    ]
}

SQL函数:

$BODY$DECLARE
    success boolean;
    msg text;
    var_most_recent json;
BEGIN


SELECT to_json(array_agg(t)) INTO var_most_recent FROM (

    SELECT *
        ( SELECT to_json(array_agg(t)) FROM (
                SELECT * FROM postPhoto AS PP WHERE post.id = PP."postId"
            )t )
    FROM post
    ORDER BY id DESC LIMIT 10

)t;

success = TRUE; msg = 'Successfully Returned Post data';
RETURN (SELECT json_build_object(
    'success', success,
    'msg', msg,
    'body', json_build_object(
        'mostRecent', var_most_recent
    )
));

END;$BODY$

1 个答案:

答案 0 :(得分:1)

我认为你错过了json_agg聚合函数。我就是这样做的:

SELECT json_agg(p)
FROM
   (SELECT
        json_build_object(
            'postId', post.id,
            'title', post.title,
            'description', post.description,
            'postPhotos',
                (SELECT json_agg(json_build_object('id',id,'name',name))
                 FROM postPhoto WHERE postId=post.id)
        ) AS p
    FROM post
    ORDER BY post.id
    LIMIT 10) as t
WHERE json_array_length(p->'postPhotos')>1;