2012-07-26 18 views
0

我有一個rails應用程序(postgres + postGIS)與一個評級列(整數)後模型。如果我進入控制檯,並做到:Postgres的偏移量/限制與mysql的工作方式不一樣嗎?

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">] 

回答

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 ] } 
#... 

這應該給你合理的,一致的結果。