PostgreSQL query works locally (9.x), but gives syntax error on Heroku (8.x)

陌路散爱 提交于 2019-12-25 08:14:16

问题


I developed my site and it works like a charm on my local machine. The query is supplied by a fellow Stackoverflow member in this thread.

schema.rb portion that is relevant

Same data locally as on Heroku.

select  *
from    (
        select  *
        ,       row_number() over (partition by odds_type order by odds_index desc) as rn2
        from    (
                select  *
                ,       row_number() over (partition by event_id, bookmaker_id, odds_type 
                                           order by created_at desc) as rn1
                from    Odds
                where   event_id = #{e.id}
                ) sub1
        where   rn1 = 1
        ) sub2
where   rn2 = 1

The error in the console

Odds Load (88.4ms)  select * from ( select *, row_number() over (partition by odds_type order by odds_index desc) as rn2 from (select *, row_number() over (partition by event_id, bookmaker_id, odds_type order by created_at desc) as rn1 from Odds where event_id = 21 ) sub1 where rn1 = 1 ) sub2where rn2 = 1
ActiveRecord::StatementInvalid: PG::Error: ERROR:  syntax error at or near "over"
LINE 1: select * from ( select *, row_number() over (partition by od...
                                           ^

回答1:


row_number() and window functions in general are available in PostgreSQL 8.4 or higher. The error indicates that you're trying this query on an older version (8.3?), so it can't work.

Update: after studying the original question and answer with PG 9.x, I believe you could obtain the same result with the PostgreSQL-specific DISTINCT ON clause, non-standard but available in older versions of PG and quite handy in your case. Here's my proposal:

SELECT DISTINCT on (ot) bi,ot,oi FROM
  (select distinct on (bi,ot) bi,ot,oi from odds
    where ei=1 order by bi,ot,created_at desc) subq
 ORDER BY ot,oi DESC;


来源:https://stackoverflow.com/questions/10995418/postgresql-query-works-locally-9-x-but-gives-syntax-error-on-heroku-8-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!