【问题标题】:PostgreSQL query works locally but not on Heroku (same data)PostgreSQL 查询在本地工作,但不在 Heroku 上(相同数据)
【发布时间】:2011-09-12 13:40:31
【问题描述】:

这里是查询:

ActiveRecord::StatementInvalid (PGError: ERROR: 在“over”处或附近出现语法错误 select *, rank() over (partition by thread_i... ^

     SELECT *
     FROM (                                                                  
             select *, rank() over (partition by thread_id order by created_at DESC)
             from posts
             where circle_id IN (134) OR (receiver_id=3)
           ) as dt
     WHERE rank = 1

编辑:这是我想要做的事情的详细解释: Rails 3 app with PostgreSQL - Getting the list of messages grouped by converstation

事实证明 Heroku 共享数据库是 PostgreSQL 8.3 版,因此没有 windows 功能,所以问题变成了如何在 PostgreSql 8.3 中执行此查询?

谢谢!

【问题讨论】:

  • Derek 和 Yahia 的派生表解决方案应该适用于 8.3。不过,posts.created_at = dt.maxdt 有可能为单个线程产生多个结果。您可能希望包含一个客户端检查来处理重复的thread_id,created_at 对。重复的可能性很低,但“低”和“零”并不完全相同。
  • 用重复问题的可能解决方案更新了我的答案...

标签: sql ruby-on-rails-3 postgresql heroku


【解决方案1】:

试试

SELECT p.*
 FROM (                                                                  
         select x.thread_id, max(x.created_at) as maxdt
         from posts x
         where x.circle_id IN (134) OR x.receiver_id=3
         group by x.thread_id
       ) as dt
 INNER JOIN posts p ON p.thread_id = dt.thread_id and p.created_at = dt.maxdt 
 ORDER BY p.created_at DESC

编辑 - 根据评论:

SELECT p.*
 FROM (                                                                  
         select x.thread_id, max(x.created_at) as maxdt, max (OID) maxo
         from posts x
         where x.circle_id IN (134) OR x.receiver_id=3
         group by x.thread_id
       ) as dt
 INNER JOIN posts p ON p.thread_id = dt.thread_id and p.created_at = dt.maxdt AND p.OID = dt.maxo
 ORDER BY p.created_at DESC

【讨论】:

  • 如果 Matteo 设法获得具有相同 thread_id,created_at 对的多个条目,那么您获得重复项的可能性非常小。不过,我会在 Ruby 中处理这种可能性。
  • 查看上面的编辑...它通过仅返回给定@987654324 组合的具有最高 OID 的记录(假设它是最新的...)来解决可能的重复问题@和created_at
  • 不错,老 oid 把戏。我会给你另一个赞成票,但我只有一个帐户 :) 遗憾的是 Heroku 没有将他们的共享数据库更新到 8.4 以获取窗口函数。在极少数情况下,我认为选择哪一个并不重要,您只需要一种方法来准确选择一个。
  • 伙计们非常感谢您的帮助!!!你们两个都为我节省了很多时间。干得好!
【解决方案2】:

这应该能让你到达那里:

 SELECT p.*
 FROM (                                                                  
         select thread_id, max(created_at) as maxdt
         from posts
         where circle_id IN (134) OR (receiver_id=3)
       ) as dt
 INNER JOIN posts p ON p.thread_id = dt.thread_id and p.created_at = dt.maxdt

【讨论】:

  • 如果 Matteo 设法获得具有相同 thread_id,created_at 对的多个条目,那么您获得重复项的可能性非常小。不过,我会在 Ruby 中处理这种可能性。
猜你喜欢
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 2013-03-29
  • 2015-02-07
相关资源
最近更新 更多