2011-11-30 74 views
0

我完全不知道這裏發生了什麼 - 我做錯了什麼?Rails/Postgresql:訂單,限制和偏移的奇怪行爲

irb(main):022:0> Toy.order('rating DESC').all.map(&:id) 
    Toy Load (2.0ms) SELECT "toys".* FROM "toys" ORDER BY rating DESC 
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] 

irb(main):029:0> Toy.order('rating DESC').limit(8).offset(0).all.map(&:id) 
    Toy Load (0.8ms) SELECT "toys".* FROM "toys" ORDER BY rating DESC LIMIT 8 OFFSET 0 
=> [2, 3, 4, 5, 6, 7, 8, 1] 

irb(main):029:0> Toy.order('rating DESC').limit(8).offset(8).all.map(&:id) 
    Toy Load (0.8ms) SELECT "toys".* FROM "toys" ORDER BY rating DESC LIMIT 8 OFFSET 8 
=> [10, 11, 12, 13, 14, 15, 16, 1] 

irb(main):029:0> Toy.order('rating DESC').limit(8).offset(16).all.map(&:id) 
    Toy Load (0.8ms) SELECT "toys".* FROM "toys" ORDER BY rating DESC LIMIT 8 OFFSET 16 
=> [18, 19, 20, 21, 22, 23, 24, 1] 

如果我沒有範圍限制和訂單偏移一切都很好。只要我添加排序,第一個對象總是出現在最後,無論我設置了什麼偏移量。任何想法爲什麼發生這種情況?謝謝!

+1

您是否嘗試過''psql' PostgreSQL shell中的SELECT ID FROM玩具ORDER BY DESC LIMIT 8 OFFSET 0'? –

回答

2

在猜測rating不是一個唯一的鍵,所以你的排序是不穩定的,並且可能會在每次使用時以不同的順序返回行。嘗試添加id的排序爲次要鑰匙,以確保排序順序是明確的,就像這樣:

Toy.order('rating DESC, id ASC').limit(8).offset(8).map(&:id) 

還請注意,你不應該需要.all,你可以直接申請map到AREL而不強迫它首先被實現。

+1

謝謝 - 就是這樣。我需要在下次分頁時使用獨特的按鍵提醒自己! – user1053134