Mysql does not use the rand () function to read database records randomly.

Source: Internet
Author: User
Tags mysql tutorial

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.