SoFunction
Updated on 2025-03-09

Method of implementing random numbers in MySQL rand function

I need to test the MYSQL database, which has a database of tens of thousands of data. How to write a PHP file and update hundreds of messages every time I write a loop to update one message at a time, so that I know that I can write it in WHILE. If I update it at a time, how to write it in 100 data! The correct answer is to use MySQL rand function: UPDATE cdb_posts SET views = rand(); By the way, I found some examples of mysql rand function, as follows: Then in the insert command, use rand() in value(), pay attention to whether the field width is enough, always think that mysql randomly query several pieces of data, use SELECT * FROM `table` ORDER BY RAND() LIMIT 5
That's it.

But after real testing, I found that this is very inefficient. A library with more than 150,000 pieces of data query, actually takes more than 8 seconds to view the official manual. It also says that rand() will be executed multiple times in the ORDER BY clause, which is naturally efficient and very low. .

Searching Google, basically searching max(id) * rand() on the Internet to randomly obtain data.

SELECT * 
FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM `table`)) AS id) AS t2 
WHERE  >=  
ORDER BY  ASC LIMIT 5;

But this will produce 5 consecutive records. The solution is to query one at a time, 5 times. Even so, it is worth it, because for 150,000 tables, the query only takes less than 0.01 seconds. The above statement uses JOIN, and someone uses it on the mysql forum

SELECT * 
FROM `table` 
WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) 
ORDER BY id LIMIT 1;

I tested it and it took 0.5 seconds and the speed was good, but it was still very different from the above statement. I always feel that something is abnormal. So I rewritten the sentence.

SELECT * FROM `table` 
WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM `table`))) 
ORDER BY id LIMIT 1;

Now, the efficiency has improved again, the query time is only 0.01 seconds, and finally, the statement is improved and the judgment of MIN(id) is added. When I first tested, I didn't add MIN(id) to judge, and half of the time I always checked the first few rows in the table.
The complete query statement is:

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 1;
SELECT * 
FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`))+(SELECT MIN(id) FROM `table`)) AS id) AS t2 
WHERE  >=  
ORDER BY  LIMIT 1;

Finally, these two statements are queryed 10 times in php.
The former takes 0.147433 seconds
The latter takes 0.015130 seconds

The above is the method of the MySQL rand function to implement random numbers.