用arel中的union重写复杂的查询?

时间:2010-08-19 13:35:00

标签: ruby-on-rails-3 arel

我有以下型号

class Courier < ActiveRecord::Base
  has_many :coverages
end

class Coverage < ActiveRecord::Base
  belongs_to :courier
  belongs_to :country_code
end

class CountryCode < ActiveRecord::Base      
end

然后我有以下查询:

# could i translate this into cleaner arel?
result = Courier.find_by_sql(<<SQL
          select * from
          (
            select cc.*, cv.rate from couriers cc, coverages cv
            where cv.country_code_id=#{country.id} and cv.courier_id=cc.id
          union
            select cc.*, cv.rate from couriers cc, coverages cv
            where cv.country_code_id is null
              and cv.courier_id=cc.id
              and cv.courier_id not in (select courier_id from coverages where country_code_id=#{country.id})
          ) as foo order by rate asc
SQL
)

简而言之:我正在寻找覆盖特定国家/地区代码的所有快递公司或使用空国家/地区代码覆盖的所有快递公司(后备)。

查询有效,但我想知道是否有更好的方法来编写它?

2 个答案:

答案 0 :(得分:1)

如果您想保留find_by_sql,可以将查询压缩为:

result = Courier.find_by_sql [
  "SELECT cc.*, cv.rate
  FROM couriers cc inner join coverages cv on cv.courier_id = cc.id
  WHERE cv.country_code_id = ?
    OR (cv.country_code_id is null AND cv.courier_id NOT IN (SELECT courier_id FROM coverages WHERE country_code_id= ? ))
  ORDER BY cv.rate asc", country.id, country.id ]

答案 1 :(得分:1)

使用arel似乎并不是很难得到类似的东西:

country_code = ...
c=Courier.arel_table
cv=Coverage.arel_table    
courier_ids_with_country_code= Coverage.select(:courier_id).where(:country_code=>country_code)
coverage_ids_and_condition= Coverage.select(:id)
                                    .where(cv[:country_code]
                                               .eq(nil)
                                               .and(cv[:courier_id]
                                                          .in(courier_ids_with_country_code)))
coverage_ids_with_country_code= Coverage.select(:id)
                                        .where(:country_code=>country_code)

coverage_union_joined_with_couriers = Coverage.include(:courier)
                                              .where(cv[:id]
                                                     .in(coverage_ids_with_country_code
                                                         .union(coverage_ids_and_condition)))

这将执行一个查询,获取给定条件的coverage和关联的信使。我不相信为了得到预期的结果而对其进行调整是非常困难的。