MySQL takes random data out of a table

Source: Internet
Author: User
Tags execution mysql rand

Implemented randomly, the following statement was found from the manual to complete the task:

SELECT * FROM table_name ORDER BY RAND () LIMIT 5;

That's what Rand said in the handbook:

RAND ()

RAND (N)

Returns a random floating-point value in the range 0 through 1.0. If an integer parameter n is specified, it is used as a seed value.

Mysql> select RAND ();

-> 0.5925

Mysql> Select RAND (20);

-> 0.1811

Mysql> Select RAND (20);

-> 0.1811

Mysql> select RAND ();

-> 0.2079

Mysql> select RAND ();

-> 0.7888

You cannot use a column with the rand () value in an ORDER BY clause, because an order by will repeatedly compute the column multiple times. In MySQL3.23, however, you can do this: SELECT * FROM table_name ORDER BY RAND (), which is advantageous to getting a from SELECT * from Table1,table2 WHERE a=b and C<d O A random sample of the collection of Rder by RAND () LIMIT 1000.

Note that a rand () in a WHERE clause will be reassessed each time the where is executed.

But try it, 8,000 records of the table, the execution once needed 0.08 sec, a little slower. After consulting Google, get the following code:

















Execution efficiency requires 0.02 sec. Unfortunately, only MySQL 4.1.* above supports such subqueries.



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.