Code to remove random data from MySQL database tables _php tutorial

Source: Internet
Author: User
How MySQL takes random data out of a table
I used to discuss this problem in the group, which is interesting. mysql syntax is fun.

They used to want to use PHP to implement random, but take out more than two times like to make more than one query.

Turn over the manual, find the following statement, you can complete the task

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

That's what Rand says in his handbook:
RAND ()
RAND (N)
Returns a random floating-point value within a range of 0 to 1.0. If an integer parameter n is specified, it is used as the 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 the order by will repeat the computed column multiple times. However in MySQL3.23, you can do: SELECT * FROM table_name ORDER by RAND (), which is advantageous to get a from SELECT * from Table1,table2 WHERE a=b and C A random sample of the collection of
But I tried, 8,000 records of the table, 0.08 sec is required to execute once. It's a little slow.

later consulted Google, get the following code

SELECT *
from table_name as R1 JOIN
(SELECT R Ound (RAND () *
(SELECT MAX (ID)
from table_name)) as ID)
as R2
WHERE r1.id >= r2.id
Orde R by R1.id ASC
LIMIT 5;

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

http://www.bkjia.com/phpjc/318428.html www.bkjia.com true http://www.bkjia.com/phpjc/318428.html techarticle mysql how to remove random data from a table the problem was discussed in the group before, and the comparison is interesting. MySQL's syntax is really fun. They used to want to use PHP to implement random, But take out a lot of it like ...

  • 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.