How do I select a random row from the database based on the probability chance assigned to each row.
Example:
Make Chance Value
ALFA ROM
You can do this by using rand()
and then using a cumulative sum. Assuming they add up to 100%:
select t.*
from (select t.*, (@cumep := @cumep + chance) as cumep
from t cross join
(select @cumep := 0, @r := rand()) params
) t
where @r between cumep - chance and cumep
limit 1;
Notes:
rand()
is called once in a subquery to initialize a variable. Multiple calls to rand()
are not desirable.limit 1
arbitrarily chooses 1.cumep > @r
.