这是数据库连接代码
require 'sequel'
DB = Sequel.connect('jdbc:mysql://localhost/idemcon?user=root&password=root&zeroDateTimeBehavior=convertToNull', :max_connections => 10)
下面是一个从MySQL表中获取列总和的查询
使用第一种方法
DB.fetch("SELECT SUM(bill) AS total FROM invoice WHERE provider = '#{provider}' AND invoicedate BETWEEN '#{fromdate}' AND '#{thrudate}';").first[:total] || 0
OR
使用map方法并在第0个索引处选择元素
DB.fetch("SELECT SUM(bill) AS total FROM invoice WHERE provider = '#{provider}' AND invoicedate BETWEEN '#{fromdate}' AND '#{thrudate}';").map(:total)[0] || 0
注意:在某些情况下我可能会为空,这就是为什么将|| 0
附加到查询末尾的原因
有更好的方法吗?如果不是我应该使用哪一个?
答案 0 :(得分:1)
这可能是做你想做的最好的方法:
DB[:invoices].
where(:provider=>provider, :invoice_date=>fromdate..thrudate).
sum(:bill)
请注意,您提供的代码最多可能有三个SQL注入漏洞,具体取决于用户是否提供了变量值。