Reputation: 67
I have a MySQL table with 3 fields as follows.
id, name, chance
1001, name1, 1
1002, name2, 3
1003, name3, 1
I want to randomly select a record 100 times. 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).
How to do that in MySQL and/or PHP?
Many thanks in advance!
Upvotes: 1
Views: 277
Reputation: 1270401
Doing this in SQL is a bit challenging. 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:
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
. This should return one row, but there is a boundary case where rand()*totchance
exactly equals sumchance
. Either row could be returned. The limit 1
limits it to one row.
Upvotes: 2
Reputation: 410
To generate a random number in php use
int rand ( int $min , int $max )
Then use a series of if statements.
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)
Upvotes: 2