如何以Ruby方式编写MySQL查询?

时间:2017-08-10 06:49:41

标签: ruby-on-rails ruby

我有一个有效的MySQL查询,当我在ActiveRecord::Base.connection.execute中传递它时返回所需的值。我想知道如何以更优化的Ruby方式编写它。

我的查询如下:

SELECT SUM(invoiceAmt) AS invoiceTotal,
       CONCAT('Q', QUARTER(invoiceDate), '(', YEAR(invoiceDate), ')') 
FROM INVOICES 
GROUP BY YEAR(invoiceDate), QUARTER(invoiceDate) 
ORDER BY YEAR(invoiceDate), QUARTER(invoiceDate)

3 个答案:

答案 0 :(得分:2)

假设您有一个名为ionic info的{​​{1}}模型,那么这些内容应该符合您的要求:

ActiveRecord

请注意,我还没有测试过该查询。这里的想法是,您可以将经过验证的查询细分传递给InvoiceInvoice.select('SUM(invoiceAmt) AS invoiceTotal, QUARTER(invoiceDate) AS q, YEAR(invoiceDate) AS y') .order('y, q') .group('y, q') #select。我使用命名别名来简化#order#group段。

答案 1 :(得分:1)

如果您没有ActiveRecord模型用于发票,则可以使用Arel。 ActiveRecord使用了Arel,因此Rails已经包含它了

invoices = Arel::Table.new(:invoices)
q = Arel::Nodes.build_quoted('Q')
open_paren = Arel::Nodes.build_quoted('(')
close_paren = Arel::Nodes.build_quoted(')')

quarter = Arel::Nodes::NamedFunction.new('QUARTER', [invoices[:invoiceDate]])
year = Arel::Nodes::NamedFunction.new('YEAR', [invoices[:invoiceDate]])

concatenated = Arel::Nodes::NamedFunction.new('concat', [q, quarter, open_paren, year, close_paren])
query = invoices.
  project(invoices[:invoiceAmt].sum.as('invoiceTotal'), concatenated).
  group(quarter, year).
  order(quarter, year)

puts query.to_sql

# SELECT SUM("invoices"."invoiceAmt") AS invoiceTotal, concat('Q', QUARTER("invoices"."invoiceDate"), '(', YEAR("invoices"."invoiceDate"), ')')
# FROM "invoices"
# GROUP BY QUARTER("invoices"."invoiceDate"), YEAR("invoices"."invoiceDate")
# ORDER BY QUARTER("invoices"."invoiceDate"), YEAR("invoices"."invoiceDate")

答案 2 :(得分:-2)

首先创建一个表格模型

其次,您需要将此模型用于INSERT / SELECT / UPDATE / DELETE任务。

https://www.sitepoint.com/orm-ruby-introduction/ 您可以看到ActiveRecord如何在这里工作;