0

I am fetching some data from the database as below in my ruby file:

@main1= $connection.execute("SELECT * FROM builds 
                WHERE   platform_type LIKE 'TOTAL';")

@main2= $connection.execute("SELECT * FROM builds 
                WHERE   platform_type NOT LIKE 'TOTAL';")

After doing this I am performing hashing and a bunch of other stuff on these results. To be clear, this does not return an array as such, but it returns some mysql2 type object. So I just map it to 2 arrays to be safe:

@arr1 = Array.new
@arr1 = @main1.map

@arr2 = Array.new
@arr2 = @main2.map

Is there any way to avoid executing 2 different queries and getting all the results in 2 different arrays by executing just one query. I basically want to split the results into 2 arrays, the first one having platform_type = TOTAL and everything else in the other one.

Pi Horse
  • 2,350
  • 8
  • 30
  • 51
  • 2
    You say you’re using Rails, but you’re not using an ORM? Any particular reason? Also your `@arr = Array.new` calls are superfluous. – Andrew Marshall Apr 04 '13 at 22:57

2 Answers2

2

Also without getting into why you're doing what you're doing, I would use Enumerable#partition as such:

rows = $connection.execute('SELECT * FROM builds')
like_total, not_like_total = rows.partition { |row|
  row['platform_type'] =~ /TOTAL/
}

Note that, IIRC, SQL LIKE 'TOTAL' isn't the same as Ruby's "string" =~ /TOTAL/ (which is more like LIKE '%TOTAL%' in SQL—am not sure what you need).

Alistair A. Israel
  • 6,417
  • 1
  • 31
  • 40
1

To answer your question without getting into why you're doing it like that:

Return them all in one query, with the extra criteria, then you can group them however you want with group_by:

all_results = $connection.execute("SELECT *, platform_type LIKE 'TOTAL' as is_like_total FROM builds").

This will give each of your results an 'is_like_total' "column" that you can group_by on.

http://ruby-doc.org/core-2.0/Enumerable.html#method-i-group_by

Clarke Brunsdon
  • 305
  • 2
  • 6