There is no built-in support from any of the known databases for random selection. If you do some searches, you may find something like:
select * from my_table order by rand();
But this is very inefficient as it tries to sort the entire table.
If your data set is not too large, you can simply output the entire table to an array and randomly select from this array.
Now the selected choice, which is more difficult.
The simplest version will work something like this:
- Get a list of all identifiers (
id) and weights ( weight ) in the table. - Iterate through the list and calculate the total weight
cwieght for each identifier. - When you reach the end of the list, you will have the total number of all weights. Choose a random number
r between 0 and this value. - Browse the list again and find the element where
r >= cweight && r < cweight+weight You can use the binary chops search if you play.
There are other more reasonable approaches to this, which depend on certain restrictions.
Michael slade
source share