This article is a mirror article of machine translation, please click here to jump to the original article.

View: 12683|Reply: 0

[Source] mysql implements a method of randomly fetching several pieces of data

[Copy link]
Posted on 7/19/2017 9:34:04 PM | | |

There are several ways to write SQL statements
1: SELECT * FROM tablename ORDER BY RAND() LIMIT The number of pieces of data you want to get;
2: SELECT *FROM 'table' WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM 'table' ) ORDER BY ID LIMIT Number of data you want to get;
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 pieces of data you want to get;
4: SELECT * FROM 'table'WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM 'table'))) ORDER BY ID LIMIT The number of pieces of data you want to get;
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 pieces of data you want to get;
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 pieces of data you want to get;
The query time of 1>> the query time of 2>> the query time of 5> the query time of 6> the query time of 4> the query time of 3, that is3 is the most efficient.




Previous:Resource sharing: Embedded STM32 project development Design and implementation of heart rate monitor
Next:[Updated] All posts on the website will be translated into English
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com