将连接计数与另一个连接列进行比较

时间:2015-01-13 03:45:34

标签: sql ruby-on-rails group-by having

我试图在

中想出我认为应该是一个非常简单的查询

相关型号:

Schedule has_many EventsEvent has_many attendees我希望得到的events attendeesevent的{​​{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

2 个答案:

答案 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)