Rails查询 - 每天的最新帖子

时间:2013-06-10 18:14:46

标签: sql ruby-on-rails

User has_many Posts。我想检索每天的最新帖子(使用created_at),忽略之前可能写过的其他帖子。提出这个问题的另一种方法可能是按部门要求每个收入最高的员工 - 我认为也是这样。

如何在Rails中编写此查询(最好是4.0)?我认为它与groupmaximum有关,但我似乎无法得到它。有没有办法在不诉诸SQL的情况下做到这一点?

为了澄清,我想要返回的是一系列帖子对象,它们是各自日期写的最后一个。

谢谢!

3 个答案:

答案 0 :(得分:2)

像这样的东西。您可以根据需要将其转换为AREL语法:

SELECT posts.created_at, *
FROM posts
INNER JOIN (
  SELECT MAX(created_at) AS max_order_date FROM posts
    GROUP BY DATE(posts.created_at)
) AS last_postings ON last_postings.max_order_date = posts.created_at
ORDER BY DATE(created_at) DESC
LIMIT 10

AREL语法可能是:

join_sql = <<-SQL
    INNER JOIN (
      SELECT MAX(created_at) AS max_order_date FROM posts
        GROUP BY DATE(posts.created_at)
    ) AS last_postings ON last_postings.max_order_date = posts.created_at
SQL
Post.joins(join_sql).order('DATE(created_at) DESC')

删除适合您的LIMIT

答案 1 :(得分:1)

它不是很干净,但这可以在Rails 3中使用(在我的案例中取自Book模型),使用PostgreSQL语法将created_at截断为日期:

max_created_at_list = Book.select("max(created_at) as created_at").group("date_trunc('day',created_at)")
last_books = Book.where(:created_at => max_created_at_list)

......或只是:

Book.where(:created_at =>Book.select("max(created_at) as created_at").group("date_trunc('day',created_at)"))

对于大型数据集,您需要created_at的索引,并且如果您使用的RDBMS没有索引空值,则create_at在数据库级别被约束为非空或“is not null”谓词(例如Oracle) )

答案 2 :(得分:0)

试试这个

Post.select("user_id, max(created_at) as created_at").group(:user_id)