12

我正在尽我最大的努力围绕 arel 和它背后的关系代数弯曲我的大脑,但是如何表示 aSELECT 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 方法,“distinct”方法是不可链接的。

于 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 方式,不是吗?不是阿雷尔的方式。

这适用于 1.x:

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,重复的行结果将被自动删除。只需使用正常的 Project (Phi) 操作即可。

于 2012-03-25T14:05:34.123 回答