[英]Selecting MySQL records with chance
I have a MySQL table with 3 fields as follows. 我有一个包含3个字段的MySQL表,如下所示。
id, name, chance
1001, name1, 1
1002, name2, 3
1003, name3, 1
I want to randomly select a record 100 times. 我想随机选择100次记录。 Out of 100 times, I want record id 1001 to be selected 20 times (1/5 chance), record id 1002 to be selected 60 times (3/5 chance), and record id 1003 to be selected 20 times (1/5 chance).
在100次中,我希望记录ID 1001被选择20次(1/5几率),记录ID 1002被选择60次(3/5次机会),并且记录id 1003被选择20次(1/5)机会)。
How to do that in MySQL and/or PHP? 如何在MySQL和/或PHP中做到这一点?
Many thanks in advance! 提前谢谢了!
To generate a random number in php use 在php中使用生成随机数
int rand ( int $min , int $max )
Then use a series of if statements. 然后使用一系列if语句。
For example: 例如:
$random = rand (1,100);
(INSERT LOOP)
if ($random <= 20){
$id1001 = $id1001 + 1;
}
else if ($random > 20 and $random < 80){
$id1002 = $id1002 + 1;
}
else if ($random > 80 and $random < 100){
$id1003 = $id1003 + 1;
}
(END LOOP)
Doing this in SQL is a bit challenging. 在SQL中执行此操作有点挑战性。 If your numbers are really so small, the easiest way is by doing a
cross join
to multiply out the records and then take a random row from there: 如果您的数字真的很小,最简单的方法是通过
cross join
来乘以记录,然后从那里取一个随机行:
select t.*
from t join
(select 1 as n union all select 2 union all select 3) n
on n.n <= t.chance
order by rand()
limit 1;
This works if "chance" is a small integer. 如果“机会”是一个小整数,这是有效的。
Otherwise, I think you need a cumulative sum of chance and then a comparison. 否则,我认为你需要累积的机会总和,然后进行比较。 Something like:
就像是:
select t.*
from (select t.*, (@sumchance := @sumchance + chance) as sumchance
from t cross join (select @sumchance := 0) const
) t cross join
(select sum(chance) as totchance from t) tot
where rand()*totchance between sumchance - chance and sumchance
limit 1;
This calculates the sum of chance up to a given row (the order doesn't make a difference because this is random). 这计算了到达给定行的机会总和(该顺序没有区别,因为这是随机的)。 It then calculates a random number in the same range and compares it to
sumchance - chance
and chance
. 然后计算相同范围内的随机数并将其与
sumchance - chance
和chance
进行比较。 This should return one row, but there is a boundary case where rand()*totchance
exactly equals sumchance
. 这应该返回一行,但是有一个边界情况,其中
rand()*totchance
完全等于sumchance
。 Either row could be returned. 可以返回任何一行。 The
limit 1
limits it to one row. limit 1
将其限制为一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.