空关系
none 方法返回可以在链式调用中使用的、不包含任何记录的空关系。在这个空关系上应用后续条件链,会继续生成空关系。对于可能返回零结果、但又需要在链式调用中使用的方法或作用域,可以使用 none 方法来提供返回值。
Article.none # 返回一个空 Relation 对象,而且不执行查询
# 下面的 visible_articles 方法期待返回一个空 Relation 对象
@articles = current_user.visible_articles.where(name: params[:name])
def visible_articles
case role
when 'Country Manager'
Article.where(country: country)
when 'Reviewer'
Article.published
when 'Bad User'
Article.none # => 如果这里返回 [] 或 nil,会导致调用方出错
end
end
计算 Aggregations
- 数量
SELECT COUNT(*) AS event_count FROM events;
对应的 Rails 语法是 Event.count
- 最小和最大值
SELECT MIN(capacity) as min_capacity FROM events;
SELECT MAX(capacity) as max_capacity FROM events;
对应的 Rails 语法是 Event.minimum(:capacity) 和 Event.maximum(:capacity)
- 总和
SELECT SUM(capacity) as sum_capacity FROM envets;
对应的 Rails 语法是 Event.sum(:capacity)
- 平均
SELECT SUM(capacity) / COUNT(capacity) as avg_capacity FROM events;
或者
SELECT AVG(capacity) as avg_capacity FROM events;
对应的 Rails 语法是 Event.average(:capacity)
- 分类 GROUP BY
SELECT users.name, COUNT(events.id) AS events_counts from users LEFT JOIN events ON users.id = events.user_id GROUP BY user_id HAVING events_counts > 1 ORDER BY events_counts DESC;
- 去除重复的数据 DISTINCT
SELECT DISTINCT(user_id) FROM events;
汉字排序
Topic.order("convert(name USING GBK)")
查询不重复
Topic .select("count(distinct order_id) as count")