轨道3:。集团()下令created_at [英] Rails 3: .group() ordered by created_at

查看:156
本文介绍了轨道3:。集团()下令created_at的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是Rails 3的方式订购。集团()导致ActiveRecord的(这里的created_at)?

What is the Rails 3 way to order .group() results in Activerecord (here by "created_at")?

@messages = Message.group(:foo)

只会导致显示最早的消息。我需要最新的中显示。

only results in displaying the oldest message. I'd need the latest to be shown.

我试过

@messages = Message.group(:foo).having("created_at = MAX(created_at)")

没有成功。任何提示AP preciated!

with no success. Any hints appreciated!

要澄清:我希望有自己内部的组有序的,不正常的messages.order(...)。 如果有不容易的ActiveRecord语法,我会很乐意与原始SQL以及

To clarify: I'm looking to have the group ordered within itself, not a normal messages.order("..."). Should there be no easy Activerecord syntax, i'd be happy with raw SQL as well

更新:尝试在SQL的方式,这是这样运作的:

Update: trying the SQL way, this was supposed to work:

@messages = Message.find_by_sql("
  SELECT messages.* 
  FROM messages 
  GROUP BY messages.foo 
  HAVING messages.created_at = MAX(messages.created_at) 
  ORDER BY messages.created_at DESC")

但是,这仅检索单记录(那些不分组)。据说分组那些被忽略。不知道为什么,所有的记录有:created_at和:FOO值

But this retrieves solely single records (those that are not grouped). Supposedly grouped ones are being omitted. Do not know why, all records have :created_at and :foo values

推荐答案

心动不如行动通过使用多个专用子查询工作,没有GROUP BY电话:

Got it all working by using a more dedicated subquery, without a GROUP BY call:

SELECT *
   FROM `messages`
   WHERE `id` = (
      SELECT `id`
      FROM `messages` as `alt`
      WHERE `alt`.`foo` = `messages`.`foo`
      ORDER BY `created_at` DESC
      LIMIT 1
   )
   ORDER BY `created_at` DESC

感谢所有在这个线程混乱的回答: MySQL的集团通过订购

不知道有任何速度的影响尚未虽然。如果有人想介入,请随时这样做。

Don't know about any speed implications yet though. If anyone wants to step in, please feel free to do so.

这篇关于轨道3:。集团()下令created_at的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆