Forum: Ruby on Rails Simple Question: How to merge SQL results?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
54a6fc785e9fcf73ead8e387432b32f5?d=identicon&s=25 Dan Harper (Guest)
on 2006-04-21 02:10
(Received via mailing list)
Hopefully an easy one, how do I merge two or more SQL query results?

Example:
   result1 = find_by_sql(x)
   result2 = find_by_sql(y)

What is the best way to merge result1 and result2?  I want to be able
to reference the objects as if they were obtained via one query.

Cheers,
Dan
B07c187ac858535358faa9365b66e657?d=identicon&s=25 John Tsombakos (Guest)
on 2006-04-21 02:28
(Received via mailing list)
On 4/20/06, Dan Harper <dan@danharper.org> wrote:
> Hopefully an easy one, how do I merge two or more SQL query results?
>
> Example:
>    result1 = find_by_sql(x)
>    result2 = find_by_sql(y)
>
> What is the best way to merge result1 and result2?  I want to be able
> to reference the objects as if they were obtained via one query.

The results are just arrays, so you can just do:

  resultset = result1 + result2
59de94a56fd2c198f33d9515d1c05961?d=identicon&s=25 Tom Mornini (Guest)
on 2006-04-21 02:31
(Received via mailing list)
This *should* work:

result =      find_by_sql(x)
result.concat find_by_sql(y)

--
-- Tom Mornini
9d1f5d2d9de70bd9a934f557dc95a406?d=identicon&s=25 Daniel ----- (liquid)
on 2006-04-21 06:51
(Received via mailing list)
You could also use a UNION caluse in your SQL
54a6fc785e9fcf73ead8e387432b32f5?d=identicon&s=25 Dan Harper (Guest)
on 2006-04-21 07:46
(Received via mailing list)
Perfect, this works a treat.

I can then even chuck a result.uniq on the return statement to
eliminate duplicate records in the result.  Ruby is so beautiful it
brings a tear to the eye...

Thanks for the tip,
Dan
0091f92762685860109bbcb02edfdf27?d=identicon&s=25 Alain Ravet (Guest)
on 2006-04-21 09:59
(Received via mailing list)
One more way :

      result = []
      result << find_by_sql(x)
      result << find_by_sql(y)
      result << find_by_sql(z)
      return result.flatten.uniq


Alain
This topic is locked and can not be replied to.