查询按关联表列排序的结果,仅查询最近的关联

时间:2010-10-10 18:19:20

标签: ruby-on-rails sorting mysql

给出以下架构

class User
  has_many :page_views
  #[id]
end

class Page
  has_many :page_views
  #[id]
end

class PageView
  belongs_to :user
  belongs_to :page
  #[id, created_at, updated_at]
end

如何按create_at日期按顺序查询给定页面,所有用户的最新页面查看次数。每个用户一行,仅显示其最近的视图。

2 个答案:

答案 0 :(得分:1)

对于特定的page_id,您希望每个user_id具有最大created_at的PageViews。这是SQL中此查询的表示形式:

SELECT max(created_at) AS last_visit, page_views.* 
FROM page_views 
WHERE (page_id = 1) 
GROUP BY user_id 
ORDER BY last_visit DESC

在Rails 3中,您可以这样写:

Page.first.page_views.group(:user_id).select('max(created_at) AS last_visit, page_views.*').order('last_visit DESC')

答案 1 :(得分:1)

试试这个:

class Page
  has_many :page_views
  has_many :recent_page_views, :class_name => "PageView",
    :joins => "INNER JOIN (
      SELECT     a.id, COUNT(*) AS ranknum
      FROM       page_views AS a
      INNER JOIN page_views AS b ON a.user_id = b.user_id AND 
                                    a.page_id = b.page_id AND 
                                    a.created_at <= b.created_at
      GROUP BY   a.id
      HAVING COUNT(*) = 1
    ) AS d ON (page_views.id = d.id)",
    :order => "page_views.created_at"

 has_many :recent_viewers, :through => :recent_page_views, 
            :source => :user, :order => "page_views.created_at"
end

现在

page.recent_viewers