mysql - 使用 ruby​​ 将多个数组中的数字相加

标签 mysql sql ruby rubygems mysql2

我正在使用 ruby​​ mysql2 gem 来处理数据库。我想在一个表中列出每个区域的所有国家/地区,然后将每个区域的点击次数相加。

通常我会使用 mysql SUM 函数,但 gem 返回 header ,因此这是不可能的。

相反,我获取每个地区每个国家/地区的点击次数并将其相加。 gem 每个结果返回 1 个数组,我需要获取该结果并将其添加到每个区域的运行总数中。

这是我的代码:

#!/usr/bin/ruby -w
# simple.rb - simple MySQL script using Ruby MySQL module

require "rubygems"
require "mysql2"

client = Mysql2::Client.new(:host => "localhost", :username => "root", :database => "cbscdn")
regions = client.query("select Id from Regions")

regions.each(:as => :array) do |rid|
  hit = client.query("select hits from Countries where Regions_Id='#{rid}'")
  hit.each(:as => :array) do |a|
    a.map do |x|
      x.to_i
    end
  end
end

如何实现每个区域的运行计数?

最佳答案

让数据库完成工作:

client.query(%q{
    select regions_id, sum(hits)
    from countries
    group by regions_id
}).each(:as => :array) do |row|
    region_id, total_hits = row
    #...
end

如果您想要不在 countries 表中的区域的总和:

client.query(%q{
    select r.id, coalesce(sum(c.hits), 0)
    from regions r
    left outer join countries c
    on r.id = c.regions_id
    group by r.id
}).each(:as => :array) do |row|
    region_id, total_hits = row
    #...
end

关于mysql - 使用 ruby​​ 将多个数组中的数字相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9289220/

相关文章:

mysql - 出现两个外键就一定是多对多关系吗?

ruby-on-rails - 我有一个评论模型,我的观点可以用什么? @评论,:comment or comment?

php - 在 php 中使用序列化将关联数组存储在数据库中

mysql - mariadb 在带有主机路径卷的 kubernetes pod 内崩溃

mysql - 从带有 introtext 的列中删除跨度

java - 使用java1001插入数据库

mysql - MySQL 中 SQL 脚本的默认数据库

mysql - Ruby:Mysql 时间戳/日期时间问题

ruby - 如何用大正则表达式加快扫描大字符串的速度?

php - MySQL 在插入时更改数字