postgresql, odd OFFSET/LIMIT behavior ( records order )

橙三吉。 提交于 2019-12-23 02:24:06

问题


so basically I have this scope(sql):

scope.to_sql
=> "SELECT  \"offers\".* FROM \"offers\" INNER JOIN \"cities_offers\" ON \"offers\".\"id\" = \"cities_offers\".\"offer_id\" WHERE \"cities_offers\".\"city_id\" = 2 AND \"offers\".\"category_id\" IN (2) AND (offers.category_id is NOT NULL) ORDER BY offers.discount desc LIMIT 25 OFFSET 0"

Somehow the records order is different for the above query and the same one without LIMIT and OFFSET:

   scope[6]
=> #<Offer id: 8629 ...

scope.except(:offset, :limit)[6]
=> #<Offer id: 8729 ...

both 8629 and 8729 records have the same discount value ( the attribute I order by ).

Could you please advice if it's possible to keep the same records ordering under these circumstances?


回答1:


Relational databases are set-based and hence inherently unordered; the order of the records in a result set is specified only by the ORDER BY clause. If two rows have the same values for the expression in the ORDER BY clause, then running the same query twice may return those rows in different positions; altering the query by adding LIMIT and OFFSET just makes things worse by making a different order more likely.

If you want the database to give you rows in a certain order, you must fully specify the order in your ORDER BY clause. You have to add more to the order call in your scope:

...order('offers.discount desc, offers.created_at asc')

or something like that depending on the specific order that you need.



来源:https://stackoverflow.com/questions/9401314/postgresql-odd-offset-limit-behavior-records-order

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