The mysql tutorial does not use the rand () function to randomly read database tutorial records.
As well as google's related files, we found that order by rand () is almost the same, but there are actually very serious performance problems.
If your database contains only a few hundred entries and the number of calls is small, you can use whatever method you like.
However, if you have 0.1 million or 1 million or more data records, each time you execute an SQL statement with order by rand, the mysql server needs to calculate 0.1 million or 1 million or more random numbers. You can imagine how much waste of resources on the database server is.
I suggest you use one of the following methods:
First: count + limit
1. select count (*) from table_name // obtain the total database records $ count
2. $ randoffset = rand (0, $ count-1 );
3. select * from table_name limit $ randoffset, 1
Type 2: maxid
1. select max (id) from table_name // obtain the maximum value of the primary key field of the database $ maxid
2. $ randid = rand (0, $ maxid );
3. select * from table_name where id> = $ randid limit 1
If you can ensure that IDs are continuous, you can even calculate a group of $ randids directly, and then extract data in batches using where id in ($ randid_1, $ randid_2 ,...).
If the id is not continuous, you can calculate multiple 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, order by rand () it is more cost-effective to calculate tens of thousands, hundreds of thousands, and millions of random numbers.