Rails - “all all”之后的“order by”

时间:2022-02-28 15:45:32

How to make this (PostgreSQL) using Rails syntax?:

如何使用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

I made following:

我做了以下:

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')

The problem is that this << is not a classical "UNION ALL", but joining of two arrays, and "order" can not be applied to the resulting array.

问题是这个< <不是经典的“union all”,而是连接两个数组,而“order”不能应用于生成的数组。< p>

1 个解决方案

#1


1  

This is a place where I tend to use find_by_sql. The results will be returned as an array with columns requested encapsulated as attributes of the model from which you call this method.

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

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

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

~Charles~

〜查尔斯〜

#1


1  

This is a place where I tend to use find_by_sql. The results will be returned as an array with columns requested encapsulated as attributes of the model from which you call this method.

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

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

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

~Charles~

〜查尔斯〜