具有连接和顺序的独特记录

时间:2014-02-23 15:23:49

标签: ruby-on-rails postgresql ruby-on-rails-4 join sql-order-by

我在UserDonations之间有一个简单的关系,因为用户有很多捐款,捐赠属于用户。 我想做的是获取最近捐款订购的用户列表。

以下是我正在尝试的内容:

首先,我想获得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

接下来,当我删除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....

然后我尝试通过显式设置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, "users".*, "donations".created_at FROM "users" INNER JOIN "donations" ON "donations"."user_id" = "users"."id" ORDER BY donations.created_at

但是,返回的记录数没有考虑DISTINCT语句并返回692条记录:

> _.size
 => 692

我如何获得预期的结果数量(384),同时按捐赠的created_at时间戳进行排序?

1 个答案:

答案 0 :(得分:21)

试试这个:

User.select('users.*,MAX(donations.created_at) as most_recent_donation').
  joins(:donations).order('most_recent_donation desc').group('users.id')

我认为用户有很多捐款,这会选择最近创建的捐款,并会选择按其ID过滤的不同用户。

我没有测试过这个。