Mysql query random data

SELECT * FROM `table` ORDER BY RAND() LIMIT 50

That’s it. But the actual test found that this efficiency is very low. In a database with more than 150,000 records, it takes more than 8 seconds to query 5 records of data
Search Google, basically query max(id) * rand() to get data randomly.

The best way is as follows:


SELECT * FROM `table`
WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`)) + (SELECT MIN(id) FROM `table`)) )
ORDER BY id LIMIT 50;

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish