返回连接表,但仅按主表ID分组

时间:2015-01-14 00:35:24

标签: postgresql sequelize.js

我正在尝试返回4个表的连接,但是将它们按“commentcount”分组。但是我不断告诉我将每个表的'id'添加到GROUP BY子句中。但这样做会为每个“commentcount”提供“1” 表:

  • 用户
  • 个人资料(加入用户(具有user_id列))
  • 帖子(加入用户(有user_id列))
  • 评论(加入帖子和用户(有user_id和post_id列))


这是我的疑问:

SELECT 
    "Post".*, 
    COUNT(*) AS "CommentCount", 
    "PostComments"."id" AS "PostComments.id", 
    "User"."id" AS "User.id", 
    "User"."email" AS "User.email", 
    "User"."password" AS "User.password",  
    "User.Profile"."id" AS "User.Profile.id", 
    "User.Profile"."user_id" AS "User.Profile.user_id", 
    "User.Profile"."username" AS "User.Profile.username", 
    "User.Profile"."gender" AS "User.Profile.gender"
FROM
    "posts" AS "Post" 
LEFT OUTER JOIN 
    "post_comments" AS "PostComments" 
       ON     "Post"."id" = "PostComments"."post_id" 
          AND "PostComments"."deleted_at" IS NULL 
LEFT OUTER JOIN 
    "users" AS "User" 
       ON     "Post"."user_id" = "User"."id" 
          AND "User"."deleted_at" IS NULL 
LEFT OUTER JOIN 
    "profiles" AS "User.Profile" 
       ON  "User"."id" = "User.Profile"."user_id" 
WHERE "Post"."deleted_at" IS NULL
GROUP BY 
    "Post"."id";

我收到错误column "User.id" must appear in the GROUP BY clause or be used in an aggregate function但是当我添加它时,columncount是错误的。

*如何按Post.id列进行分组,仍然可以从连接表中获取相应的数据? *

N.B。一旦我弄明白,我想将正确的查询转换为sequelize.js,所以如果有人碰巧知道如何用续集,我会更受欢迎:)

1 个答案:

答案 0 :(得分:1)

我希望此查询会给出每篇帖子的评论数量。

select "post_id", count(*) as num_comments
from "PostComments"
group by "post_id";

现在,无论您的查询的其余部分是什么,您都可以从上面的查询加入“post_id”。这些方面的东西应该有效。

select ..., comment_count.num_comments
from ...
-- other joins go here . . .
left outer join (select "post_id", count(*) as num_comments
                 from "PostComments"
                 group by "post_id") comment_count
    on "Post"."id" = comment_count.post_id
where "Post"."deleted_at" is null;