在Ruby中的另一个循环中迭代MySql查询结果

时间:2016-07-14 03:52:11

标签: mysql ruby-on-rails ruby rubygems

是否有任何解决方案可以使用ruby在另一个循环中迭代一个MySql query结果。

使用Ruby mysql Gem

在我的代码fetch_row中不接受任何参数。所以我的代码会返回错误。

connection = Mysql.new(@db_host, @db_user, @db_pass, @db_name)
total_make = connection.query("Select make COUNT(cartype) AS cnt FROM vehicles group by car order by car;")
result = connection.query("Select make, cartype, COUNT(cartype) AS cnt FROM vehicles where cartype='suv' group by car order by car;")
suv = 0
data = ""
i = 0
result.each do |row|
    suv += row[1].to_i
    total_make.fetch_row(i)
    data +=  row[0] + "\n"
    data += "Total Cars: " + total_make[1] + "\n"
    data += "Total SUV : " + suv.to_s + "\n"
    data += "-----------------------\n"
    data = ""
    i+=1
end

puts data

MySql查询:

Select make, cartype, COUNT(cartype) AS cnt FROM vehicles where cartype='suv' group by car order by car;

+-----------+-----------+-----+
|    make   |  cartype  | cnt |
+-----------+-----------+-----+
|    Ford   |    suv    |   2 |
|   Toyota  |    suv    |   3 |
+-----------+-----------+-----+

Select make COUNT(cartype) AS cnt FROM vehicles group by car order by car;

+-----------+-----+
|    make   | cnt |
+-----------+-----+
|    Ford   |   4 |
|   Toyota  |   5 |
+-----------+-----+

预期结果:

尝试通过制作和列出总车辆来分组汽车,总计suv。

Totota
Total Cars: 5
Total SUV : 3
-----------------------
Ford
Total Cars: 4
Total SUV : 2
-----------------------

2 个答案:

答案 0 :(得分:0)

我不是100%清楚你究竟要求的是什么,或者如何使用mysql宝石充分利用它,但这就是我如何以Rails的方式产生你期望的结果。

#in the controller
@cars = Cars.all


#in the view
<% @cars.group_by{|a| a[:make]}.each do |key, group| %>
  <%= key %><br>
  Total Cars: <%= group.size %><br>
  Total SUV: <%= group.where(:cartype => "suv").size %><br>
  ------------------
<% end %>

答案 1 :(得分:0)

试试吧。我没有测试过它。

i=0
result.each do |row|

total_make.first(i).each do |make|
make_count_value = make['cnt'] 
end 

data += "Total Cars: " + row['cnt'] "\n"
data += "Total SUV : " + make_count_value "\n"
data += "-----------------------\n"
data = ""

i=i+1
end