我想检索具有许多活动的联系人,其中后者的最大completed_date是6个月前。让我说清楚:
user = User.first
user.contacts.first.activities.maximum(:completed_date)
# SELECT MAX("activities"."completed_date") AS max_id FROM "activities" WHERE "activities"."user_id" = $1 [["user_id", 12]]
=> 2014-03-18 09:06:54 UTC
多数民众赞成。现在我想为WHERE查询使用该子句,但似乎我不能:
user.contacts.joins(:activities)
.where('MAX("activities"."completed_date") < ?', Time.now - 6.months)
# SELECT "contacts".* FROM "contacts"
# INNER JOIN "activities" ON "activities"."contact_id" = "contacts"."id"
# WHERE "contacts"."user_id" = $1 AND (MAX("activities"."completed_date") <= '2013-09-23 05:55:21.191254') [["user_id", 12]]
#=> PG::GroupingError: ERROR: aggregate functions are not allowed in WHERE
# LINE 1: ...ntacts"."id" WHERE "contacts"."user_id" = $1 AND (MAX("activ...
我该怎么做?
答案 0 :(得分:5)
由于MAX
聚合函数调用了WHERE
子句,因此抱怨。
要避免此问题,请MAX
SELECT
与AS
混淆WHERE
。然后使用user.contacts.select('*, MAX("activities"."completed_date") AS max_complete_date').joins(:activities)
.where('max_complete_date < ?', Time.now - 6.months)
中的别名。
HAVING
修改强>
我道歉,您应该使用 user.contacts.joins(:activities)
.having('MAX("activities"."completed_date") < ?', Time.now - 6.months).group("contacts.id")
代替。
{{1}}