There is no native support from any of the known databases for a random select. IF you do some searches you might find something like:
select * from my_table order by rand();
But that is woefully inefficient as it attempts to sort the entire table.
If your data set is not too big, you can simply pull the entire table into an array and select randomly from that array.
Now wieghted selection, that is more tricky.
A simpler version would work out something like this:
- Get a list of all of the ids (
id)
and weights (weight
) in the table.
- Iterate through the list and calculate the cumulative weight
cwieght
for each id.
- When you reach the end of the list you will have a total of all of the weights. Select a random number
r
between 0 and that total.
- Scan through the list again and find the item where
r >= cweight && r < cweight+weight
You can use a binary chop search for this if you are game.
There are other smarter approaches to this as well, which depend on certain restrictions.