浏览 2479 次
锁定老帖子 主题:Rails中查询mysql的一点技巧
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-07-09
最后修改:2009-07-16
示例如下: Person.average('age') # => 35.8 支持的方法如下:
求最小值通过类似group by的语法: values = Person.maximum(:age, :group => 'last_name') puts values["Drake"] => 43 drake = Family.find_by_last_name('Drake') values = Person.maximum(:age, :group => :family) # Person belongs_to :family puts values[drake] => 43 values.each do |family, max_age| ... end 其中允许的参数包括:
示例如下: Person.calculate(:count, :all) # The same as Person.count Person.average(:age) # SELECT AVG(age) FROM people... Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for everyone with a last name other than 'Drake' Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name) # Selects the minimum age for any family without any minors Person.sum("2 * age") count应用如下: Person.count(:conditions => "age > 26") Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN. Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") # finds the number of rows matching the conditions and joins. Person.count('id', :conditions => "age > 26") # Performs a COUNT(id) Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*') 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |