How To Randomly Select From A Record Based On Weight (PHP, MySQL)

Share on facebook
Share on google
Share on twitter
Share on linkedin

I got this code from a brilliant comment here, and it’s a simple formula that allows you to randomly select from a database. The difference is, each record is weighted and the random sampling also takes that into account.

For example, this will be very useful if you have several people in your database, and you wanted to randomly select them, but based on how well you liked them. This would be an example of your database:

| id | weight | Person    |
|  1 |     70 | Person A  |
|  2 |     20 | Person B  |
|  3 |     10 | Person C  |
|  4 |     90 | Person D  |
|  5 |     10 | Person E  |

And the MySQL statement that you’d use is:

SELECT person from people order by -LOG(RAND())/weight desc limit 5

Similar Posts:

More to explorer

how i started being a minimalist

How I Started Being A Minimalist

Once, I thought that all that mattered in life were the things that you possessed. Things like your car, house, watch, clothes.

Leave a Reply

Your email address will not be published. Required fields are marked *