Random order with MySql pagination

1

Hello, I am having to randomly sort result from my query and display paging using mysql. The sort and pagination are working perfectly.

Whenever pagination is done, because of the use of ORDER BY RAND(); , the results are random and repeated in pagination.

I would like to know how to use ORDER BY RAND(); so that the records always appear random in each query (not necessarily on each page) without repeating on the following pages.

SELECT * FROM tabela1 WHERE Id= $id ORDER BY RAND() LIMIT $inicial,$final
    
asked by anonymous 28.06.2017 / 20:23

1 answer

2

What you can do is:

SELECT * FROM (
    SELECT * FROM tabela1 LIMIT $inicial, $final
) as t
ORDER BY RAND();

In this way, paging records are selected by% internal% and are then ordered randomly. Without doing this, SELECT is executed before RAND , then each page runs the risk of duplicate records (understand duplicate as already displayed on another page), because as the order will be random, you can not guarantee which will be the records between LIMIT and $inicial .

  

See working in SQLFiddle .

    
28.06.2017 / 21:08