我在下面有以下查询。问题是我在执行时抛出了这个错误:
column "v4.id" must appear in the GROUP BY clause or be used in an aggregate function
这没有多大意义,因为我没有在聚合函数中使用该字段。关于这是为什么的任何想法?
SELECT c0."id",
c0."assigned_user_id",
c0."assigned_team_id",
c0."last_activity",
c0."last_message",
c3."unread_count",
c0."closed",
v4."name",
v4."avatar",
v4."id",
Count(c0."id") OVER()
FROM "conversations" AS c0
LEFT OUTER JOIN "apps" AS a1
ON a1."id" = c0."app_id"
LEFT OUTER JOIN "conversation_users" AS c5
ON c5."conversation_id" = c0."id"
LEFT OUTER JOIN "users" AS u2
ON c5."user_id" = u2."id"
LEFT OUTER JOIN "conversation_users" AS c3
ON c3."conversation_id" = c0."id"
LEFT OUTER JOIN "visitors" AS v4
ON v4."id" = c0."visitor_id"
WHERE ( a1."id" = $1)
AND ( u2."id" = $2)
AND ( c3."user_id" = $3)
GROUP BY c0."id",
ORDER BY c0."last_activity" DESC ["ASnYW1-RgCl0I", "clt8ojxvk0000dp2fyvwq126", "clt8ojxvk0000dp2fyvwq126"]
答案 0 :(得分:3)
完全为什么你想要group by
中的列。从形式上讲,您应该在group by
中确实拥有所有非聚合列:
group by c0."id", c0."assigned_user_id", c0."assigned_team_id",
c0."last_activity", c0."last_message", c0."closed",
c3."unread_count",
v4."name", v4."avatar", v4."id"
Postgres有一个扩展(由ANSI标准支持),让您可以替换group by
中的主键或唯一键,并仍可访问其他列。我没有将它用于多个表,但这可能也有效:
group by c0."id",
c3."unread_count",
v4."id"
此外,您的选择是使用窗口功能。你为什么在那里有over
条款?这是一个聚合查询,因此在此上下文中没有意义。