私は脳をアレルとその背後にある関係代数の周りに曲げるために最善を尽くしていますが、aを表現する方法SELECT DISTINCT
は一貫して私の理解を逃しています。誰もがアレルする方法を説明できますか?
SELECT DISTINCT title FROM posts;
どうもありがとう!
私は脳をアレルとその背後にある関係代数の周りに曲げるために最善を尽くしていますが、aを表現する方法SELECT 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メソッドと同様に、「個別の」メソッドは連鎖できません。
それを行うためのArelの方法は次のとおりです。
t = Arel::Table.new(:foo)
count_distinct = t[:field].count(true)
count_distinct.to_sql # => "COUNT(DISTINCT `foo`.`field`)"
前の答えはRailsの方法ですよね?アレルの方法ではありません。
これはarel1.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を使用するため、重複する行の結果は自動的に削除されます。通常のプロジェクト(Phi)操作を使用するだけです。