简体   繁体   中英

How to generate a random range to get fields from mysql database, given number of records, and range limit

Haven't programmed in a while and here I am with this simple problem, basically I need to generate two random numbers that are within a maximum limit, but with set distance apart from each other in order to randomly (each time) call fields from the database using the mysql LIMIT.

ex. say there are 95 database fields ($max), fields returned = 20 ($fields) (number of fields that should be returned) or range limit 20 (ie difference between min - max is 20)

SELECT...............  LIMIT $a, $fields
$a - $b = 20
$b < 95

I just use ...

 $a = floor(mt_rand(0, ($max-$fields))); 

to generate an $a and use the $fields value which gives me all the info I need (ie from where to start getting the records ($a) and how many records to get ($fields))

Any ideas on another way on how to do this?

If your table is always bigger then the required distance of the two random numbers you can go about it like this:

// $row_count is the number of rows you have in the database 
$max = mt_rand($distance, $row_count);
$min = $max - $distance;
// now you can use these in sql like
$sql = "select ... offset {$min} limit {$distance}";

References: mt_rand

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM