How to obtain random data from mysql

Source: Internet
Author: User

1. order by rand ()
The data is too slow and the randomness is very good. It is suitable for situations with very small data volumes.
Copy codeThe Code is as follows:
SELECT * FROM table_name AS r1 JOIN (SELECT (ROUND (RAND () * (select abs (MAX (id)-MIN (id)-$ limit) FROM table_name )) + (select min (id) from table_name) AS id) AS r2 WHERE r1.id> = r2.id order by r1.id asc limit $ limit;

The speed is very fast, but the obtained data is sequential with IDs, which cannot be solved.
The subquery generates a random number.
Rand () is a random number ranging from 0 to 1, which can be 0 to 1.
MAX (id)-MIN (id) also needs to subtract $ limit to avoid the number of results being less than $ limit
Because the primary table id may be discontinuous, r1.id must be> = r2.id
Note that sometimes the minimum id does not start from 1 and may start from a large number. Therefore, the M (id) value must be added.
Manual content: If you want to obtain a random integer R in the range of I ≤ R ≤ j, you need to use the expression FLOOR (I + RAND () * (j-I + 1 )).
For example, to get a random integer in the range of 7 to 12 (including 7 and 12), you can use the following statement:
Copy codeThe Code is as follows:
Select floor (7 + (RAND () * 6 ));
Select * from test where rand ()> 0.0005 limit 10;
 

0.0005 is a calculated proportion that is directly related to the random quality. For example, if a data table contains 10000 million data records and 300 data records need to be randomly retrieved, 0.0005 needs to be changed to (300/10000 = 0.03 ).
This method does not guarantee how much data can be obtained each time. It must be obtained multiple times.
2 and 3 are as fast as they are. The main difference is that 2 can always return limit data records, and 3 may be possible (in line with the normal distribution ). 2 is continuous data, 3 is random rows.

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.