【问题标题】:Rails - "order by" after "union all"Rails - “union all”之后的“order by”
【发布时间】:2012-06-19 14:29:11
【问题描述】:

如何使用 Rails 语法制作这个(PostgreSQL)?:

SELECT fld1, fld2
FROM
(
    SELECT fld1, fld2, count(*) as cnt FROM data WHERE fld2 not in('exclude1', 'exclude2') GROUP BY fld1, fld2 ORDER BY COUNT(*) DESC LIMIT 100
    UNION ALL
    SELECT fld1, fld2, count(*) as cnt FROM data WHERE fld2 in('exclude1', 'exclude2') GROUP BY fld1, fld2
) x
ORDER BY x.cnt DESC

我做了以下:

my_data = (Data.all(
    :select => sel_clause,
    :conditions => "data.fld2 not in %s" % [in_clause],
    :group => grp_clause,
    :order => 'count(*) desc',
    :limit => @max_rows) <<
    Data.all(
        :select => sel_clause,
        :conditions => "data.fld2 in %s" % [in_clause],
        :group => grp_clause).order('cnt desc')

问题是这个

【问题讨论】:

    标签: ruby-on-rails activerecord sql-order-by union-all


    【解决方案1】:

    这是我倾向于使用 find_by_sql 的地方。结果将作为一个数组返回,其中请求的列封装为您从中调用此方法的模型的属性。

    http://ar.rubyonrails.org/classes/ActiveRecord/Base.html

    ~查尔斯~

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 2010-09-26
      • 2020-01-18
      • 1970-01-01
      相关资源
      最近更新 更多