Home >Backend Development >PHP Problem >How to get several pieces of data randomly in php mysql

How to get several pieces of data randomly in php mysql

藏色散人
藏色散人Original
2022-01-06 09:09:573118browse

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.

How to get several pieces of data randomly in php mysql

#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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn