【问题标题】:SQL Query converting to Rails Active Record Query InterfaceSQL 查询转换为 Rails 活动记录查询接口
【发布时间】:2014-05-21 11:04:35
【问题描述】:

我一直在我的 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 |

【问题讨论】:

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


    【解决方案1】:

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

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

    像这样,

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

    【讨论】:

      【解决方案2】:

      您可以使用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")
      

      【讨论】:

        猜你喜欢
        • 2011-10-24
        • 1970-01-01
        • 2015-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多