Home >Database >Mysql Tutorial >How to implement random numbers using MySQL rand function_MySQL
I need to test the MYSQL database. There is a database with tens of thousands of data. How do I write a PHP file to update hundreds of pieces of information at a time? I always write a loop to update one piece of information at a time, so I know that writing with WHILE is enough. , if one update is like 100 pieces of data, how to write it! The correct answer is to use the MySQL rand function: UPDATE cdb_posts SET views = rand(); By the way, I will find you some examples of the mysql rand function, as follows: Then use rand() in the insert command, value(), pay attention to the fields Is the width enough? I always thought that mysql randomly queries a few pieces of data, so use SELECT * FROM `table` ORDER BY RAND() LIMIT 5
That's it.
But after a real test, I found that this is very inefficient. For a database with more than 150,000 items, it takes more than 8 seconds to query 5 pieces of data. Check the official manual. It is also said that rand() will be executed multiple times in the ORDER BY clause, which is naturally very inefficient. .
Search Google, basically query 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 t1.id >= t2.id ORDER BY t1.id ASC LIMIT 5;
But this will produce 5 consecutive records. The solution can only be to query one query at a time, 5 times. Even so, it is worth it, because querying a table with 150,000 entries only takes less than 0.01 seconds. The above statement uses JOIN, and someone on the mysql forum uses it
SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;
I tested it, it takes 0.5 seconds, the speed is good, but there is still a big gap with the above statement. I always feel like something is not normal. So I reworded 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. Finally, improve the statement and add the judgment of MIN(id). When I first tested, it was because I did not add the MIN(id) judgment that the first few rows in the table were always queried half the time.
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 t1.id >= t2.id ORDER BY t1.id LIMIT 1;
Finally, query these two statements 10 times in php,
The former takes 0.147433 seconds
The latter takes time 0.015130 seconds
The above is how the MySQL rand function implements random numbers.