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.
Dan H. (Guest)
on 2006-04-21 04: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
John T. (Guest)
on 2006-04-21 04:28
(Received via mailing list)
On 4/20/06, Dan H. <removed_email_address@domain.invalid> 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
Tom M. (Guest)
on 2006-04-21 04:31
(Received via mailing list)
This *should* work:

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

--
-- Tom M.
Daniel -. (Guest)
on 2006-04-21 08:51
(Received via mailing list)
You could also use a UNION caluse in your SQL
Dan H. (Guest)
on 2006-04-21 09: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
Alain R. (Guest)
on 2006-04-21 11: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.