2015-01-14 46 views
0

我想返回4個表的連接,但通過「commentcount」將它們分組。但是我保持gettng一個錯誤,告訴我將每個表的'id'添加到GROUP BY子句中。但這樣做提供了每個 「commentcount」 表 '1':返回連接表,但只由主表ID編號

  • 用戶
  • 配置文件(連接到用戶(已經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,一旦我找到了它,所以如果有人碰巧知道如何使用sequelize做到這一點,我會更歡迎:)

+0

Postgresql does not工作爲mysql,讓您添加任何字段與聚合函數whitout抱怨。如果您使用聚合,例如'count(*)'你應該在'group by'語句中添加你選擇的所有字段。 –

+0

CREATE TABLE語句是描述表格的最佳方式。將這些粘貼到您的問題中。 –

回答

1

我' d期望這個查詢給出每個帖子的評論數量。

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; 
+0

即使我聲明'LEFT OUTER JOIN'post_comments「AS」PostComments「',在子查詢中,我必須將'PostComments''替換爲'from'from'post_comments」'。之後,它完美的工作!謝謝。 – DBrowne