Optimization of random retrieve records in Mysql rand ()

Source: Internet
Author: User

In mysql, the Rand () function is used to query random data in a data table. However, the Rand () function uses tens of thousands of records quickly, if tens of millions of records may cause problems, let's introduce the usage of the Rand () function.

MySQL randomly queries a record.

The Code is as follows: Copy code


$ SQL = "SELECT * FROM pinglun WHERE id> = (SELECT MAX (id) FROM pinglun)-(SELECT MIN (id) FROM pinglun) * RAND () + (select min (id) FROM pinglun) LIMIT 1 ″;

In this way, the write efficiency is relatively high. Do not use order by rand (). If the data volume is large, the order efficiency is very low.


Next I will introduce the optimization of random retrieve records.


Method 1:

Combined with the application layer

Select max (id) FROM table; obtain the largest id, and then generate a random 1 ~ MAX (id) number, such as PHP mt_rand (1, MAX (id), and then query the record with this random id.

Method 2:

Use the random id generated by the database and subquery Method

The Code is as follows: Copy code
Select ceil (RAND () * (select max (id) FROM table ));

In this way, we can obtain a random id. (optimize MAX () without using select ceil (RAND () * MAX (id) FROM table). Execute the following command to greatly optimize

The Code is as follows: Copy code


SELECT *
FROM table
WHERE id> = (
Select ceil (RAND ()*(
Select max (id)
FROM table )))
LIMIT 1


Method 3:
JOIN Method

The Code is as follows: Copy code

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 1

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.