ActiveRecord:组合两个* COMPLEX * ActiveRecord结果

时间:2014-03-18 01:59:19

标签: sql ruby-on-rails select activerecord union

我有一个使用UNION的SQL查询,我尝试将其更改为ActiveRecord查询。它如下:

(SELECT town FROM town_health_records 
  WHERE percent_publicly_financed_prenatal_care_2005_to_2008 IS NOT NULL 
    ORDER BY percent_publicly_financed_prenatal_care_2005_to_2008 
      DESC LIMIT 10)
        UNION 
          (SELECT town 
            FROM town_health_records 
              WHERE total_infant_deaths_2005_to_2008 IS NOT NULL 
                AND 
                  town != 'Massachusetts Total' 
                    ORDER BY total_infant_deaths_2005_to_2008 
                      DESC LIMIT 10);

我一直在尝试一些东西,但它似乎不起作用(Spaced易于使用):

TownHealthRecord.select("town")
  .where("percent_publicly_financed_prenatal_care_2005_to_2008 IS NOT NULL")
    .order("percent_publicly_financed_prenatal_care_2005_to_2008")
      .union(TownHealthRecord.select("town")
        .where("total_infant_deaths_2005_to_2008 IS NOT NULL AND town !=        
          'Massachusetts Total'")
            .order("total_infant_deaths_2005_to_2008")
              .first(10))

1 个答案:

答案 0 :(得分:0)

标准ActiveRecord中没有UNION支持。您可以使用find_by_sql方法,或在数据库中创建视图