我试图在
中想出我认为应该是一个非常简单的查询相关型号:
Schedule
has_many
Events
和Event
has_many
attendees
。 我希望得到的events
attendees
比event
的{{1}} schedule
列指定的min_attendees
少。{ /强>
SELECT "events".* FROM "events"
INNER JOIN "schedules" ON "schedules"."id" = "events"."schedule_id"
INNER JOIN "attendees" ON "attendees"."event_id" = "events"."id"
GROUP BY events.id
HAVING COUNT(attendees.id) < schedules.min_attendee
尝试上述查询时出现以下错误:
ERROR: column "schedules.min_attendees" must appear in the GROUP BY clause or be used in an aggregate function
答案 0 :(得分:2)
您可以通过在其上使用聚合函数来解决此问题:
SELECT "events".*
FROM "events" INNER JOIN
"schedules"
ON "schedules"."id" = "events"."schedule_id" INNER JOIN
"attendees"
ON "attendees"."event_id" = "events"."id"
GROUP BY events.id
HAVING COUNT(attendees.id) < MIN(schedules.min_attendee)
或者,将其包含在group by
:
SELECT "events".*
FROM "events" INNER JOIN
"schedules"
ON "schedules"."id" = "events"."schedule_id" INNER JOIN
"attendees"
ON "attendees"."event_id" = "events"."id"
GROUP BY events.id, schedules.min_attendee
HAVING COUNT(attendees.id) < schedules.min_attendee
答案 1 :(得分:1)
如果你没有在scheduleles.min_attendee附近放置聚合函数,那么它应该存在于group中,否则不需要。
这可能有助于你
SELECT "events".* FROM "events"
INNER JOIN "schedules" ON "schedules"."id" = "events"."schedule_id"
INNER JOIN "attendees" ON "attendees"."event_id" = "events"."id"
GROUP BY events.id
HAVING COUNT(attendees.id) < MAX(schedules.min_attendee)
您可以使用MAX或MIN,因为每行都会有所不同。 无论您使用SELECT的哪一列必须在GROUP BY子句中,否则它将抛出错误(它必须出现在group by子句或agg f&#39; n)