我想返回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做到這一點,我會更歡迎:)
Postgresql does not工作爲mysql,讓您添加任何字段與聚合函數whitout抱怨。如果您使用聚合,例如'count(*)'你應該在'group by'語句中添加你選擇的所有字段。 –
CREATE TABLE語句是描述表格的最佳方式。將這些粘貼到您的問題中。 –