【问题标题】:How to get first value of a column using sequel and ruby?如何使用 sequel 和 ruby​​ 获取列的第一个值?
【发布时间】:2018-02-15 05:52:35
【问题描述】:

这里是数据库连接代码

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

使用 map 方法并选择第零个索引处的元素

DB.fetch("SELECT SUM(bill) AS total FROM invoice WHERE provider = '#{provider}' AND invoicedate BETWEEN '#{fromdate}' AND '#{thrudate}';").map(:total)[0] || 0

注意:在某些情况下我可能会得到 null,所以这就是为什么将 || 0 附加到查询末尾

有没有更好的方法?如果不是,我应该使用哪一个?

【问题讨论】:

  • SUM(bill) 应该返回一行。为什么需要使用 MAP 对其进行迭代?

标签: ruby sequel


【解决方案1】:

这可能是做你想做的最好的方式:

DB[:invoices].
  where(:provider=>provider, :invoice_date=>fromdate..thrudate).
  sum(:bill)

请注意,您提供的代码最多可能存在三个 SQL 注入漏洞,具体取决于变量值是否由用户提供。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2019-08-03
    相关资源
    最近更新 更多