我在用户和捐赠之间有一个简单的关系,即用户有很多捐赠,捐赠属于用户.我想做的是获取最近捐赠的用户列表.
@H_403_2@这是我正在尝试的:
@H_403_2@首先,我想获得uniq用户的总数,这是按预期工作的:
> User.joins(:donations).order('donations.created_at').uniq.count (3.2ms) SELECT DISTINCT COUNT(DISTINCT "users"."id") FROM "users" INNER JOIN "donations" ON "donations"."user_id" = "users"."id" => 384@H_403_2@接下来,当我删除count方法时,出现“ORDER BY表达式必须出现在选择列表中”的错误:
> User.joins(:donations).order('donations.created_at').uniq User Load (0.9ms) SELECT DISTINCT "users".* FROM "users" INNER JOIN "donations" ON "donations"."user_id" = "users"."id" ORDER BY donations.created_at PG::InvalidColumnReference: ERROR: for SELECT DISTINCT,ORDER BY expressions must appear in select list LINE 1: ...ON "donations"."user_id" = "users"."id" ORDER BY donations....@H_403_2@然后我尝试通过显式设置SELECT子句来修复Postgres错误,该子句乍一看似乎有效:
> User.select('DISTINCT "users".id,"users".*,"donations".created_at').joins(:donations).order('donations.created_at') User Load (17.6ms) SELECT DISTINCT "users".id,"donations".created_at FROM "users" INNER JOIN "donations" ON "donations"."user_id" = "users"."id" ORDER BY donations.created_at@H_403_2@但是,返回的记录数不考虑DISTINCT语句并返回692条记录:
> _.size => 692@H_403_2@如何根据捐赠的created_at时间戳排序,获得预期的结果数(384)?