如何将2个相关数据集加载到一起? (即帖子和评论)

时间:2015-05-05 18:28:18

标签: sql postgresql node-postgres

我对pg很新,并试图弄清楚将一组帖子及其相关评论加在一起的最佳方法是什么。

例如: 我正在尝试获取与所有这些帖子相关的10个帖子和评论,例如facebooks wall,在那里您可以看到在同一页面上加载的帖子和评论。我的架构看起来像这样:

Posts
--------
id  -  author   -  description  -  date   -  commentCount 

Comments
-------
id  -   post_id  -  author  -  description   -   date

我尝试在同一个postgres函数中加载帖子和评论,执行以下操作:

select *
from posts
LEFT join comments on posts.id = comments.post_id

不幸的是,它复制了N次评论存在的帖子,其中N是帖子的评论数量。 然而,第一个解决方案是我总是可以在获取数据后在Node中过滤它

此外,当我尝试通过posts.id使用group(以便在节点中更容易遍历)时,我收到以下错误:

column "comments.id" must appear in the GROUP BY clause or be used in an aggregate function

我可以尝试的第二个事情是发送一个我想要加载的post_ids数组并加载pg_function并将它们发送回去,但我不能正确查询:

CREATE OR REPLACE FUNCTION "getPosts"(postIds int[])
  RETURNS text AS
$BODY$
BEGIN
    RETURN (
        SELECT * 
        FROM Comments
        WHERE Comments.id = postIds[0]
    );
END;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

称呼它:

SELECT n FROM "public"."getPosts"(array[38]) As n;

但是,即使尝试从一个索引获取值,我也会收到以下错误:

ERROR:  subquery must return only one column
LINE 1: SELECT (
               ^
QUERY:  SELECT (
        SELECT * 
        FROM Comments
        WHERE Comments.id = 38
    )

最后,最后一个解决方案是简单地进行N个单独的postgres调用,其中N是带有注释的帖子数量,所以如果我有5个帖子带有评论,我会调用5个postgres post_id并从评论表中选择。

我真的不知道该怎么做,任何帮助都会受到赞赏。

由于

1 个答案:

答案 0 :(得分:0)

将所有评论作为每个帖子的记录数组:

select
    p.id, p.title, p.content, p.author,
    array_agg(c) as comments
from
    posts p
    left join
    comments c on p.id = c.post_id
group by 1, 2, 3, 4

每个评论栏都有一个数组:

select
    p.id, p.title, p.content, p.author,
    array_agg(c.author) as comment_author,
    array_agg(c.content) as comment_content
from
    posts p
    left join
    comments c on p.id = c.post_id
group by 1, 2, 3, 4