12

私は脳をアレルとその背後にある関係代数の周りに曲げるために最善を尽くしていますが、aを表現する方法SELECT DISTINCTは一貫して私の理解を逃しています。誰もがアレルする方法を説明できますか?

SELECT DISTINCT title FROM posts; 

どうもありがとう!

4

6 に答える 6

16

純粋な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メソッドと同様に、「個別の」メソッドは連鎖できません。

于 2012-09-18T21:29:29.093 に答える
13

それを行うためのArelの方法は次のとおりです。

t = Arel::Table.new(:foo)
count_distinct = t[:field].count(true)
count_distinct.to_sql # => "COUNT(DISTINCT `foo`.`field`)"
于 2014-05-29T21:33:04.173 に答える
7

前の答えはRailsの方法ですよね?アレルの方法ではありません。

これはで機能します。

posts = Table(:posts)
posts.project(Arel::Distinct.new(posts[:title]))

APIを介してこれを行う別の「より正しい」方法があると思いますが、私はまだそれを理解していません。

于 2010-08-19T18:47:51.773 に答える
3

スコープを使用してこれを行う場合:

  scope :recent, lambda {|count|
    select("DISTINCT posts.*").
    joins(:whatever).
    limit(count).
    order("posts.updated_at DESC")
  }
于 2011-02-01T00:04:12.563 に答える
1

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.

于 2010-06-29T00:28:35.420 に答える
0

ARELは常にSETを使用するため、重複する行の結果は自動的に削除されます。通常のプロジェクト(Phi)操作を使用するだけです。

于 2012-03-25T14:05:34.123 に答える