[英]Random row selection with different probabilities
I'm searching for a way to get from a table with 400-500 rows 1 random row but not with all the same probability. 我正在寻找一种方法来从具有400-500行的表中获得1个随机行,但概率不相同。
For example: My table looks like: 例如:我的表如下所示:
Object - Rank 对象-等级
I got 3 possible ranks for an object and I would like that an object with the rank "Top" got three times more chance to get taken. 我对一个对象有3个可能的等级,而我希望等级为“最高”的对象获得三倍的机会。 It should be like there are 3 rows with Object_A in the table.
就像表中有3行带有Object_A的行。 Same for Normal but only two times the chance.
与“普通”相同,但机会只有两倍。
For now I got this code... 现在我得到了这段代码...
$result = mysqli_query($link, "SELECT * FROM objects ORDER BY RAND() LIMIT 1");
let's say your rank column has these three values: 假设您的等级列具有以下三个值:
3 top
2 normal
1 low
Then what you can do is: 然后,您可以做的是:
$rand = rand()%3 +1;
$result = mysqli_query($link, "
SELECT * FROM (
SELECT * FROM objects ORDER BY RAND()
) as t
WHERE rank >= {$rand} LIMIT 1"
);
The key is to understand the where condition: rank >= {$rand}
. 关键是要了解where条件:
rank >= {$rand}
。
== 3
, 33% chances, only 1 top record will be returned. == 3
,机会为33%,则仅返回1个最高记录。 == 2
, 33% chances, only 1 top record (50% chances) or 1 normal record (50% chances) will be returned, and so on. == 2
,有33%的机会,将仅返回1个最高记录(50%的机会)或1个正常记录(50%的机会),依此类推。 You can adjust the weight by assigning a different number. 您可以通过分配其他数字来调整重量。
For example if you want the top row returned about ~80% of the times you can assign top the value of 10 and then do: 例如,如果您希望最上面的行返回大约80%的时间,则可以为top赋值10,然后执行以下操作:
$rand = rand()%10 +1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.