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.