Mysql method for obtaining random data _ MySQL

Source: Internet
Author: User
Mysql method for obtaining random data bitsCN.com

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.

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: to obtain a random integer R in the range of I ≤ R ≤ j, the expression FLOOR (I + RAND () * (j

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.