ORDER BY random() with seed in SQLITE

前端 未结 4 827
别跟我提以往
别跟我提以往 2020-12-11 00:19

I would like to implement paging for a random set

Select * from Animals ORDER BY random(SEED) LIMIT 100 OFFSET 50  

I tried to set int to

4条回答
  •  Happy的楠姐
    2020-12-11 01:11

    I would not usually copy an existing answer, but I can see that you have left a comment asking the author of this answer to explain how it works already a few weeks ago and no explanation has been given. I will therefore copy the relevant part and try to explain whats going on. If this explanation is good, do go and vote on the original answer.

    $seed = md5(mt_rand());
    $prng = ('0.' . str_replace(array('0', 'a', 'b', 'c', 'd', 'e', 'f'), array('7', '3', '1', '5', '9', '8', '4'), $seed )) * 1;
    $query = 'SELECT id, name FROM table ORDER BY (substr(id * ' . $prng . ', length(id) + 2)';
    

    The first two rows are just about creating a seed of a sort. The result is a decimal number with lots of decimals like:

    0.54534238371923827955579364758491
    

    Then the sql select uses this number to multiply with the numeric row id of every row in the SQLite table. And then the rows are sorted according to the decimal part of the resulting product. Using fewer decimals, the sort order would look something like this:

    row id   row id * seed      sort order
    1        0.545342384        545342384
    2        1.090684767        090684767
    3        1.636027151        636027151
    4        2.181369535        181369535
    5        2.726711919        726711919
    6        3.272054302        272054302
    7        3.817396686        817396686
    8        4.362739070        362739070
    

    After sorting this would be the result:

    row id   row id * seed      sort order
    2        1.090684767        090684767
    4        2.181369535        181369535
    6        3.272054302        272054302
    8        4.362739070        362739070
    1        0.545342384        545342384
    3        1.636027151        636027151
    5        2.726711919        726711919
    7        3.817396686        817396686
    

    In this sample I used only eight rows so the result is not very random looking. With more rows the result will appear more random.

    This solution will give you the same order repeatedly as long as:

    • You use the same seed
    • No new rows have appeared in the table and no rows have been deleted from the table

提交回复
热议问题