Randomly remove a record from the MySQL datasheet

Source: Internet
Author: User
Tags rand table name

Today, I went to a network construction company in Suzhou for an interview, the boss gave me a question: how to take a random piece of data from a datasheet in PHP?

Of course, at the end of my code there is a mistake, not in the real sense of random data. Back home, quickly Baidu, this just know how to randomly access data.

The rest of the code is not much to say, here's how to tell you the core Lookup data table code:

The code is as follows Copy Code

SELECT * FROM table name ORDER by rand () limit 1; The 1 here is the number of strips that take out the data

But this data on the Internet, some people say the efficiency is very poor, then how to improve it

Search Google, the Internet is basically query Max (ID) * RAND () to randomly obtain data.

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 5;

But this gets the 5 consecutive records. The solution can only be a query one at a time, query 5 times, but this is not enough to meet my requirements, I want to find a few

Efficient writing

The code is as follows Copy Code

SELECT * from user WHERE userId >= (select MAX (userId) to user)-(select MIN (userId) from user) * RAND () + (Selec T MIN (userId) from user) LIMIT 5

This test found to meet my requirements and to test 10W data at the same time is only 0.0 seconds very fast.

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.