MySQL randomly extracts 10 pieces of data from 10 million pieces of data
Direct use of order by rand() is definitely not high performance. The following two methods are used:
The first is implemented using msyql
SQL
select * from articles where id>=(select floor(rand() * (select max(id) from articles))) order by id limit 10
The rand function returns a random number of 0 and 1, and then multiplies it by the maximum id in the table, then rounds it down, and finally uses the id greater than or equal to this number to order by, and then limit it with limit, which can be efficiently checked. .
The second use program to achieve:
First, generate 10 non-repeating random numbers
$count = 0;
$return = [];
while ($count < 10) {
$return[] = mt_rand(1, 10000000);
// Deduplicating arrays is faster than array_unique
$return = array_flip(array_flip($return));
$count = count($return);
}
//Scramble the array and re-assign the new subscript to the array
shuffle($return);
Then query through mysql in
SQL
select * from articles where id in(22,26,24) order by id limit 10
0 Comments