我有一个通知模式和一个用户模式,其中用户有许多通知,通知在用户之间发送。我需要一个函数来获取每个用户的最新通知,并按时间戳排序返回它们。
我试过使用select distinct..订单:

@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
我试着用选择…分组按…订单:
@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')

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

最佳答案

试试这个:

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

documentation开始:
DISTINCT ON表达式必须与最左边的ORDER BY表达式匹配。
您必须根据错误消息重新处理第二个查询。

关于sql - Rails选择最新的顺序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37288104/

10-11 03:41
查看更多