Rails选择不同的顺序和最近的

时间:2016-05-18 00:03:34

标签: sql ruby-on-rails ruby postgresql

我有一个通知模式和一个用户模式,其中用户有许多通知,并且用户之间发送通知。我需要一个函数来获取每个用户的最新通知,并按时间戳排序返回它们。

我尝试使用SELECT DISTINCT .. ORDER BY:

@notifications = Notification.select("DISTINCT(notifier_id, created_at)").order('created_at DESC')

生成此SQL:SELECT DISTINCT(notifier_id, created_at) FROM "notifications" ORDER BY "notifications"."created_at" DESC, created_at DESC)

但我收到错误:SELECT DISTINCT, ORDER BY expressions must appear in select list

created_at确实出现在选择列表中,那么问题是什么?

根据这篇文章:PG::Error: SELECT DISTINCT, ORDER BY expressions must appear in select list

我尝试使用SELECT ... GROUP BY .. ORDER BY:

@notifications = Notification.select("notifier_id").group("notifier_id").order("MAX(created_at)")

生成此SQL:SELECT "notifications"."notifier_id" FROM "notifications" GROUP BY notifier_id ORDER BY "notifications"."created_at" DESC, MAX(created_at)

但现在我收到此错误:column "notifications.created_at" must appear in the GROUP BY clause or be used in an aggregate function

我正在使用聚合函数,那么错误是什么?

更新:

使用此代码:

@notifications = Notification.select("DISTINCT ON (created_at) created_at, notifier_id").order('created_at DESC')

我收到所有邮件的列表,而不是每个发件人的最新信息。

1 个答案:

答案 0 :(得分:2)

试试这个:

@messages = Message.select("DISTINCT ON (created_at) created_at, sender_id").order('created_at DESC')

来自documentation

  

DISTINCT ON表达式必须与最左边的ORDER BY表达式匹配。

您必须根据错误消息重新编写第二个查询。