php Mysql method to randomly obtain several pieces of data: 1. Obtain data through "SELECT * FROM tablename ORDER BY RAND() LIMIT"; 2. Obtain specified items through "ORDER BY t1.id ASC LIMIT" Number of data, etc.
#The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.
php How does mysql obtain several pieces of data randomly?
Mysql method to obtain several pieces of data randomly
There are several ways to write sql statements:
1: SELECT * FROM tablename ORDER BY RAND() LIMIT The number of data items you want to obtain;
2: SELECT *FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT The number of data items you want to obtain;
3: 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 The number of data items you want to obtain;
4: SELECT * FROM `table`WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM ` table`))) ORDER BY id LIMIT The number of data items you want to obtain;
5: SELECT * FROM `table` WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`)) (SELECT MIN(id) FROM `table`))) ORDER BY id LIMIT The number of data items you want to obtain;
6: SELECT * FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`)) (SELECT MIN(id) FROM `table`)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT The number of data items you want to obtain;
Feedback:
Accurately measured 380,000 data, randomly selected 10 1 values, and the execution time is 1-2 seconds. 2. No response after running for more than 20 seconds. I tried 3 times. 3 The 10 pieces of data taken are consecutive IDs, and the execution takes 0.001 seconds. 4 Randomly select 10 items with IDs between 1-4000, execute for 0.003 seconds, and try more than 10 times. 5 Randomly select 10 items with IDs between 1-4000, execute for 0.003 seconds, and try more than 10 times. 6 The 10 pieces of data taken are consecutive IDs, and the execution takes 0.001 seconds.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to get several pieces of data randomly in php mysql. For more information, please follow other related articles on the PHP Chinese website!