SQL查询转换为Rails活动记录查询接口

时间:2014-05-21 11:04:35

标签: sql ruby-on-rails activerecord active-record-query

我一直在我的rails代码中使用sql查询,需要转换为Active Record Query。我之前没有使用过Active Record,因此我尝试通过http://guides.rubyonrails.org/active_record_querying.html来获得正确的语法,以便能够切换到获取数据的方法。我能够将简单查询转换为这种格式,但还有其他复杂的查询,如

SELECT b.owner, 
       Sum(a.idle_total), 
       Sum(a.idle_monthly_usage) 
FROM   market_place_idle_hosts_summaries a, 
       (SELECT DISTINCT owner, 
                        hostclass, 
                        week_number 
        FROM   market_place_idle_hosts_details 
        WHERE  week_number = '#{week_num}' 
               AND Year(updated_at) = '#{year_num}') b 
WHERE  a.hostclass = b.hostclass 
       AND a.week_number = b.week_number 
       AND Year(updated_at) = '#{year_num}' 
GROUP  BY b.owner 
ORDER  BY Sum(a.idle_monthly_usage) DESC 

我需要采用Active Record格式,但由于复杂性,我不知道如何继续进行转换。

查询的输出是这样的

+----------+-------------------+---------------------------+
| owner    | sum(a.idle_total) | sum(a.idle_monthly_usage) |
+----------+-------------------+---------------------------+
| abc      |               485 |         90387.13690185547 |
| xyz      |               815 |         66242.01857376099 |
| qwe      |               122 |        11730.609939575195 |
| asd      |                80 |         9543.170425415039 |
| zxc      |                87 |         8027.090087890625 |
| dfg      |                67 |         7303.070011138916 |
| wqer     |                76 |         5234.969814300537 |

2 个答案:

答案 0 :(得分:2)

您可以使用find_by_sql方法,而不是将其转换为有效记录。由于您的查询有点复杂。

您也可以直接使用ActiveRecord::Base.connection来获取记录。

像这样,

ActiveRecord::Base.connection.execute("your query") 

答案 1 :(得分:1)

您可以使用ActiveRecord创建子查询,并使用to_sql将其转换为sql

然后使用joins将您的表格ab加入,即它是子查询。还要注意使用活动记录子句 select,where,group和order ,它们基​​本上是在ActiveRecord中构建此复杂SQL查询所需的。

类似于以下内容将起作用:

subquery = SubModel.select("DISTINCT ... ").where(" ... ").to_sql

Model.select("b.owner, ... ")
  .joins("JOIN (#{subquery}) b ON a.hostclass = b.hostclass")
  .where(" ... ")
  .group("b.owner")
  .order("Sum(a.idle_monthly_usage) DESC")