有机会选择MySQL记录


Selecting MySQL records with chance

我有一个MySQL表,其中有3个字段,如下所示。

id, name, chance
1001, name1, 1
1002, name2, 3
1003, name3, 1

我想随机选择一张唱片100次。在100次中,我希望记录id 1001被选择20次(1/5机会),记录id 1002被选择60次(3/5机会),并且记录id 1003被选择20次/5机会。

如何在MySQL和/或PHP中做到这一点?

非常感谢!

要在php中生成随机数,请使用

int rand ( int $min , int $max )

然后使用一系列if语句。

例如:

$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)

在SQL中执行此操作有点困难。如果你的数字真的很小,最简单的方法是做一个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;

如果"chance"是一个小整数,则此操作有效。

否则,我认为你需要一个机会的累积总和,然后进行比较。类似于:

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;

这会计算到给定行的机会总和(顺序没有区别,因为这是随机的)。然后,它计算相同范围内的随机数,并将其与sumchance - chancechance进行比较。这应该返回一行,但存在rand()*totchance恰好等于sumchance的边界情况。可以返回任一行。limit 1将其限制为一行。