When working with MySQL, there may be instances where you need to generate a random value that falls within a specified range. While the RAND() function exists, it does not fulfill this requirement. This article delves into the best approach for achieving this in MySQL.
The optimal method in MySQL to generate a random value within a specified range is:
ROUND((RAND() * (max-min)) min)
This formula multiplies RAND() by the difference between max and min, adding min to the result. ROUND() is applied to obtain an integer value.
The PHP equivalent of the MySQL solution is:
rand($min, $max)
However, benchmarks have shown that the MySQL solution is slightly faster when dealing with a large number of values. The choice between PHP and MySQL depends on the number of rows being processed and whether only the random value is needed or additional columns will be returned.
To obtain a random value between 10 and 200:
SELECT ROUND((RAND() * (200-10)) 10) AS `foo`
To further illustrate the performance differences, the following PHP script was run:
// MySQL
$start = microtime(1);
for( $i = 0; $i The results show that MySQL is faster for generating random values if only the random value is needed, but slower if additional columns are returned.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3