这是一个古老的问题,给定一个具有属性"类型","变化"和"价格"的表格,您可以获取每种类型的最低价格的记录.
在SQL中,我们可以做这样的:
select f.type, f.variety, f.price from ( select type, min(price) as minprice from table group by type ) as x inner join table as f on f.type = x.type and f.price = x.minprice;`
我们也许可以通过以下方式模仿:
minprices = Table.minimum(:price, :group => type) result = [] minprices.each_pair do |t, p| result << Table.find(:first, :conditions => ["type = ? and price = ?", t, p]) end
有没有比这更好的实施?
Table.minimum(:price, :group => :type)
见http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-minimum更多信息,.