我有一个 Railsfind_by_sql
方法可以在本地、控制台和语句中正常工作,也可以直接在 Postgresql 中使用,但是ActiveRecord::StatementInvalid
当我将它部署到 Heroku 时,该语句会导致错误。
我在本地运行 Postgresql 版本 9.0.3,并在其 Cedar 堆栈上的 Heroku 上使用共享数据库。
我得到的错误是:
PG::Error: ERROR: syntax error at or near "WITH normal_items" LINE 1: WITH normal_items AS (SELECT normal_items_month, count(id)... ^ : WITH normal_items AS (SELECT normal_items_month, count(id) as normal_items_total FROM (SELECT date_trunc('month',created_at) as normal_items_month, id from items WHERE items.a_foreign_key_id IS NULL) z group by normal_items_month), special_items AS (SELECT special_items_month, count(id) as special_items_total FROM (SELECT date_trunc('month',created_at) as special_items_month, id from items WHERE items.a_foreign_key_id IS NOT NULL) x group by special_items_month ) SELECT to_char(month, 'fmMon') as month, coalesce(normal_items_total, 0) as normal_items_total, coalesce(special_items_total, 0) as special_items_total FROM (select generate_series(min(normal_items_month), max(normal_items_month), '1 month'::interval) as month FROM normal_items) m LEFT OUTER JOIN normal_items ON normal_items_month = month LEFT OUTER JOIN special_items ON special_items_month = month
为便于阅读,声明如下:
WITH normal_items AS (SELECT normal_items_month, count(id) as normal_items_total
FROM (SELECT date_trunc('month',created_at) as normal_items_month, id from items
WHERE items.a_foreign_key_id IS NULL) z
group by normal_items_month),
special_items AS (SELECT special_items_month, count(id) as special_items_total
FROM (SELECT date_trunc('month',created_at) as special_items_month, id from items
WHERE items.a_foreign_key_id IS NOT NULL) x
group by special_items_month )
SELECT
to_char(month, 'fmMon') as month,
coalesce(normal_items_total, 0) as normal_items_total,
coalesce(special_items_total, 0) as special_items_total
FROM (select generate_series(min(normal_items_month), max(normal_items_month), '1 month'::interval) as month FROM normal_items) m
LEFT OUTER JOIN normal_items ON normal_items_month = month
LEFT OUTER JOIN special_items ON special_items_month = month
这只是为我提供了一些与 Google Charts 一起使用的统计信息,输出为:
Jun 178 0
Jul 0 0
Aug 72 0
Sep 189 0
Oct 24 0
Nov 6 0
Dec 578 0
Jan 0 0
Feb 0 0
Mar 89 0
Apr 607 0
May 281 0
Jun 510 0
Jul 190 0
Aug 0 0
Sep 501 0
Oct 409 0
Nov 704 0