MySQL does not use the rand () function to implement random read database records method

Source: Internet
Author: User
Keywords Web programming MySQL Tutorial
Tags calls data files function google google + google+ mysql

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 second: 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 the ID is guaranteed to be 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
    if the ID is not contiguous, 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, it's always better than the order by rand () It takes tens of thousands of hundreds of thousands of millions of random numbers to be more cost-effective.
 

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.