postgres偏移/限制不能像mysql一样工作吗?

时间:2012-07-26 20:06:46

标签: ruby-on-rails ruby-on-rails-3 postgresql postgis

我有一个带有评级栏(整数)的帖子模型的rails app(postgres + postGIS)。如果我进入控制台并执行:

Post.order("rating DESC").map(&:id)
=> [9, 15, 19, 6, 17, 5, 4, 16, 1, 3, 13, 20, 14, 10, 8, 12, 7, 2, 18, 11]

然而,如果我尝试使用限制和偏移一次循环通过那些,我会得到奇怪的结果。

Post.order("rating DESC").limit(1).offset(0)
=> [#<Post id: 5, body: "Hi", rating: 4, location: #<RGeo::Geographic::SphericalPointImpl:0x81bb34c0 "POINT (-118.495 34.017)">, user_id: 8, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]

为什么那篇文章#5?它应该是#9。无论如何,当我应用偏移时,它会变得更加怪异。

>Post.order("rating DESC").limit(1).offset(1)
=> [#<Post id: 5, body: "Hi", rating: 4, location: #<RGeo::Geographic::SphericalPointImpl:0x81bb34c0 "POINT (-118.495 34.017)">, user_id: 8, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]

>Post.order("rating DESC").limit(1).offset(2)
=> [#<Post id: 5, body: "Hi", rating: 4, location: #<RGeo::Geographic::SphericalPointImpl:0x81bb34c0 "POINT (-118.495 34.017)">, user_id: 8, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]

>Post.order("rating DESC").limit(1).offset(3)
=> [#<Post id: 5, body: "Hi", rating: 4, location: #<RGeo::Geographic::SphericalPointImpl:0x81bb34c0 "POINT (-118.495 34.017)">, user_id: 8, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]

>Post.order("rating DESC").limit(1).offset(4)
=> [#<Post id: 15, body: "I luv coffee", rating: 4, flagged: 0, location: #<RGeo::Geographic::SphericalPointImpl:0x82260df4 "POINT (-118.495 34.017)">, user_id: 1, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]

1 个答案:

答案 0 :(得分:3)

您是否注意到rating对于您展示的唯一结果是4?您正在排序rating而没有辅助排序键,因此无法保证将显示哪些订单关系,或者甚至在两个不同的呼叫中以相同的方式对关系进行排序。

尝试在order

中添加一个平局
Post.order('rating DESC, id')

然后将rating包含在您正在查看的内容中:

Post.order('rating desc, id').select('id, rating').map { |p| [ p.id, p.rating ] }
Post.order('rating desc, id').select('id, rating').limit(1).offset(3).map { |p| [ p.id, p.rating ] }
#...

这应该给你明智和一致的结果。