MySQL pseudo random number generator is completely deterministic. The docs say:
RAND () is not intended for a perfect random generator. This is a quick way to generate on-demand random numbers that carry across platforms for the same version of MySQL.
It cannot use / dev / random, because MySQL is designed to work with various operating systems, some of which do not have / dev / random.
MySQL initializes the initial default value at server startup using the integer returned by time(0) . If you are interested in the source string, this is in the MySQL source in the sql / mysqld.cc file, function init_server_components() . I do not think he ever seeds again.
Then the subsequent "random" numbers are based solely on the seed. See source file mysys_ssl / my_rnd.cc, function my_rnd() .
The best solution for your random selection task, both for performance and for the quality of randomization, is to generate a random value between the minimum primary key value and the maximum primary key value. Then use this random value to select the primary key in the table:
SELECT ... FROM MyTable WHERE id > $random LIMIT 1
The reason you will use> instead of = is that you may have spaces in the identifier due to deleting or rolling back lines, or you may have other conditions in the WHERE clause so that you have spaces between lines that match your conditions.
The disadvantages of this larger method are:
- Lines following such a gap have a higher chance of choice, and the larger the gap, the higher the probability.
- Before creating a random value, you need to know MIN (id) and MAX (id).
- Doesn't work if you need some random strings.
Advantages of this method:
- This is much faster than ORDER BY RAND (), even for a small table size.
- You can use a random function outside of SQL.
source share