开发者

How to randomize (and paginate) large set of results?

开发者 https://www.devze.com 2023-03-28 20:13 出处:网络
I am creating a contest application that requires the main index page of entries to be randomized. As it will potentially be a large set of entries (maybe up to 5000), I will also need to paginate the

I am creating a contest application that requires the main index page of entries to be randomized. As it will potentially be a large set of entries (maybe up to 5000), I will also need to paginate them.

Here are the challenges:

  1. I have read that using a database's 'random()' function on a large set can perform poorly.
  2. I would like for things to not be re-randomized when the pagination links are clicked. In other words, it should return a random set upon first load and then keep the same order while someone uses the pagination.

The secon开发者_开发百科d challenge seems potentially unrealistic, but perhaps there are some create solutions out there?

Thanks for any input.


a simple way I suggest is writing your own random function with SQL query, for the function more complicated the more random, for example:

you already know

select * from your_table order by rand() limit 0, 10

assume your_table has a primary key "id", now replace "rand()" with "MOD(id, 13)"

select * from your_table order by MOD(id, 13) limit 0,10

if your_table has a datetime column, the result would be better, try this query:

select * from your_table order by MOD(id, 13), updated_at limit 0,10

also if you don't think it's not random enough, there is I bet you love it:

select * from your_table order by MD5(id) limit 0, 10


I would just use a random number generator to select IDs, and store the seed in the session so a user will see the same ordering while paginating. I would probably also use a hash to make sure each ID is picked only once.

0

精彩评论

暂无评论...
验证码 换一张
取 消