MySQL tutorials do not use the rand () function to implement random read database Tutorial records method
, as well as Google the relevant files, and found that everyone almost exclusively use ORDER by RAND () to achieve this, but in fact there are very serious performance problems.
If your database has only hundreds of, and the number of calls is not many times, you love what method to use what method.
But if you have 100,000 or 1 million or more data, the MySQL server needs to compute 100,000 or 1 million or more random numbers each time you execute an SQL statement with order by Rand, and you can imagine how much resources are wasted on the database server.
I suggest that you use one of the following methods:
First: Count + limit
1. Select COUNT (*) from table_name//get to the total database record $count
2, $randoffset = rand (0, $count-1);
3, select * FROM table_name limit $randoffset, 1
The second type: MAXID
1. Select Max (ID) from table_name//Get the maximum value of the database primary key field $MAXID
2, $randid = rand (0, $MAXID);
3, select * FROM table_name where id>= $randid limit 1
If you can ensure that IDs are contiguous, you can even work out a set of $randid, and then use the Where ID in ($randid _1, $randid _2, ...) to extract the data in batches
& nbsp; If the ID is not continuous, you can use a number of random numbers, and then where ID in ($randid _1, $randid _2, ... $randid _100) limit 10, although I calculated 100 random numbers to extract 10 records. , but it's always worth more than tens of thousands of hundreds of thousands of millions of random numbers in order by rand ().