简体   繁体   English

如何生成随机范围以从mysql数据库获取字段,给定记录数和范围限制

[英]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. 我已经有一段时间没有编程了,这里我遇到了这个简单的问题,基本上,我需要生成两个最大数以内的随机数,但彼此之间要有一定的距离,以便随机(每次)调用来自使用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) 假设有95个数据库字段($ max),返回的字段= 20($ fields)(应返回的字段数)或范围限制20(即,最小值-最大值之差为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)) 生成$ a并使​​用$ fields值,该值为我提供了我需要的所有信息(即从哪里开始获取记录($ a)和要获取多少记录($ 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 参考: mt_rand

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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