PHP MySQL pagination with random ordering

后端 未结 6 1595
生来不讨喜
生来不讨喜 2020-12-05 11:25

This is a problem with a ordering search results on my website,

When a search is made, random results appear on the content page, this page includes pagination too.

6条回答
  •  情话喂你
    2020-12-05 11:35

    The combination of

    1. random ordering
    2. pagination
    3. HTTP (stateless)

    is as ugly as it comes: 1. and 2. together need some sort of "persistent randomness", while 3. makes this harder to achieve. On top of this 1. is not a job a RDBMS is optimized to do.

    My suggestion depends on how big your dataset is:

    Few rows (ca. <1K):

    • select all PK values in first query (first page)
    • shuffle these in PHP
    • store shuffled list in session
    • for each page call select the data according to the stored PKs

    Many rows (10K+):

    This assumes, you have an AUTO_INCREMENT unique key called ID with a manageable number of holes. Use a amintenace script if needed (high delete ratio)

    • Use a shuffling function that is parameterized with e.g. the session ID to create a function rand_id(continuous_id)
    • If you need e.g. the records 100,000 to 100,009 calculate $a=array(rand_id(100,000), rand_id(100,001), ... rand_id(100,009));
    • $a=implode(',',$a);
    • $sql="SELECT foo FROM bar WHERE ID IN($a) ORDER BY FIELD(ID,$a)";
    • To take care of the holes in your ID select a few records too many (and throw away the exess), looping on too few records selected.

提交回复
热议问题