【问题标题】:Rails inner join two sql statements to get ActiveRecord::RelationRails inner join 两条sql语句获取ActiveRecord::Relation
【发布时间】:2012-09-26 14:04:06
【问题描述】:

我有复杂的查询,我想加入自己以进行额外的计算。在sql中我可以做

SELECT t1.*, t2.*
FROM (SQL) AS t1
INNER JOIN
(SQL) AS t2
ON t1.num = t2.num - 1

假设 SQL 是我要加入的查询。

如何在 Rails 中使用 ActiveRecord / arel(或其他东西)来获取 ActiveRecord::Relation 并能够在其上使用 where()。

如果我使用 sql 和 execute/select_all 执行此操作,我会得到 PG:result 或 hash 并且不能再使用 where 方法。

【问题讨论】:

    标签: ruby-on-rails activerecord arel


    【解决方案1】:

    第一个解决方案是使用 to_sql 方法插入其他查询:

    Place.select("places.*, communes.*").joins("INNER JOIN (#{
      Commune.where(:id => [1,2,3]).to_sql
    }) as communes ON communes.id = places.commune_id")
    

    第二种解决方案是使用 Arel 的 merge 方法:

    Place.select("places.*, communes.*")
      .joins(:commune)
      .merge(Commune.where(:id => [1,2,3]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      相关资源
      最近更新 更多