Simple Question: How to merge SQL results?


#1

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


#2

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


#3

This should work:

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


– Tom M.


#4

You could also use a UNION caluse in your SQL


#5

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


#6

One more way :

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

Alain