如何使用 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')
问题是这个 << 不是经典的“UNION ALL”,而是两个数组的连接,“order”不能应用于结果数组。