Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch distinct values with arel/relational algebra

I'm doing my best to bend my brain around arel and the relational algebra behind it, but how to represent a SELECT DISTINCT is consistently eluding my comprehension. Can anyone explain how to arel:

SELECT DISTINCT title FROM posts; 

Many thanks!

like image 464
jemmons Avatar asked Jun 28 '10 21:06

jemmons


3 Answers

Using pure Arel (not Rails/ActiveRecord) there is a "distinct" method:

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"'

Curiously, the "distinct" method is not chainable, per the other Arel methods.

like image 133
maerics Avatar answered Oct 29 '22 09:10

maerics


The Arel way to do it is:

t = Arel::Table.new(:foo)
count_distinct = t[:field].count(true)
count_distinct.to_sql # => "COUNT(DISTINCT `foo`.`field`)"
like image 14
rafb3 Avatar answered Oct 29 '22 11:10

rafb3


The previous answer is the Rails way, no? Not the Arel way.

This works for arel 1.x:

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

I'd guess there's another "more correct" way to do this via the API but I haven't figured that out yet.

like image 7
numbers1311407 Avatar answered Oct 29 '22 11:10

numbers1311407