我正在尽我最大的努力围绕 arel 和它背后的关系代数弯曲我的大脑,但是如何表示 aSELECT DISTINCT
一直是我无法理解的。谁能解释一下如何做:
SELECT DISTINCT title FROM posts;
非常感谢!
我正在尽我最大的努力围绕 arel 和它背后的关系代数弯曲我的大脑,但是如何表示 aSELECT DISTINCT
一直是我无法理解的。谁能解释一下如何做:
SELECT DISTINCT title FROM posts;
非常感谢!
使用纯 Arel(不是 Rails/ActiveRecord)有一个“不同的”方法:
Arel::VERSION # => '3.0.2'
posts = Arel::Table.new(:posts)
posts.project(posts[:title])
posts.distinct
posts.to_sql # => 'SELECT DISTINCT "posts"."title" FROM "posts"'
奇怪的是,根据其他 Arel 方法,“distinct”方法是不可链接的。
Arel 的做法是:
t = Arel::Table.new(:foo)
count_distinct = t[:field].count(true)
count_distinct.to_sql # => "COUNT(DISTINCT `foo`.`field`)"
上一个答案是 Rails 方式,不是吗?不是阿雷尔的方式。
这适用于arel 1.x:
posts = Table(:posts)
posts.project(Arel::Distinct.new(posts[:title]))
我猜还有另一种“更正确”的方法可以通过 API 做到这一点,但我还没有弄清楚。
如果您使用范围执行此操作:
scope :recent, lambda {|count|
select("DISTINCT posts.*").
joins(:whatever).
limit(count).
order("posts.updated_at DESC")
}
Post.select('DISTINCT title')
Update 1:
At the time of the post, this was not available in Arel. These days, ActiveRecord::QueryMethods has the uniq
method (http://apidock.com/rails/ActiveRecord/QueryMethods/uniq), so you'd want:
Post.select(:title).uniq
Update 2: Looks like Arel now supports this behavior. @maerics has the correct answer. I'd delete this if it wasn't the accepted answer.
由于 AREL 在其操作中始终使用 SET,重复的行结果将被自动删除。只需使用正常的 Project (Phi) 操作即可。