0

我可以只使用 afind_by_sql来完成此操作,但如果可能的话,我想以 Rails 方式进行。

我的 SQL 查询如下所示:

SELECT regions.id, max(updated_at) FROM demographics 
JOIN regions ON (regions.id = demographics.region_id) 
JOIN region_stats ON (region_stats.region_id = regions.id) 
WHERE region_stats.income_level = 1    
GROUP BY demographics.region_id;

有没有办法将它干净地转换为 Rails?

4

2 回答 2

1
Demographic.find(:all,
  :conditions=>[
    "region_stats.income_level = ?",
    1
  ],
  :joins=>"as demographics JOIN regions ON (regions.id = demographics.region_id) JOIN region_stats ON (region_stats.region_id = regions.id)",
  :group=>"demographics.region_id",
  :select=>"regions.id, demographics.max(updated_at)"
)
于 2012-10-10T20:39:45.550 回答
1

未经测试:

Demographic.joins(:region => [:region_stats]).select('demographics.region_id, max(demographics.updated_at) as `max_date`').where(:region_stats => {:income_level => 1}).group('demographics.region_id')
于 2012-10-10T20:49:28.463 回答