[转帖]Rails中查询mysql的一点技巧_MySQL, Oracle及数据库讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  MySQL, Oracle及数据库讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 1367 | 回复: 0   主题: [转帖]Rails中查询mysql的一点技巧        下一篇 
ad222888
注册用户
等级:新兵
经验:66
发帖:134
精华:0
注册:2016-9-25
状态:离线
发送短消息息给ad222888 加好友    发送短消息息给ad222888 发消息
发表于: IP:您无权察看 2018-8-6 10:47:34 | [全部帖] [楼主帖] 楼主

ActiveRecode允许直接调用mysql的一些语法。这样一些例如sum avg count的mysql语法就可以非常方便的得以表达。

示例如下:

Person.average('age')
# => 35.8


支持的方法如下:

# average
# calculate
# count
# maximum
# minimum
# sum


求最小值通过类似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


其中允许的参数包括:

    * :conditions - 和Finder语法一样,例如"administrator = 1" or [ "user_name = ?", username ].

 * :include: Eager loading, see Associations for details. Since calculations don‘t load anything, the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
* :joins - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed). The records will be returned read-only since they will have attributes that do not correspond to the table‘s columns.


    * order - 用于排序 "created_at DESC, name" (really only used with GROUP BY calculations).
    * :group - 分组 Uses the GROUP BY SQL-clause.

 * :select - By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not include the joined columns.
* :distinct - Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) …


示例如下:

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 '*')




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论