March 29

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


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

Other posts about scaling up businesses

How To Choose Digital Marketing Channels (A Powerful 6 Step Process)

Leave a Reply

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
free playbook

Get Your Free 5E Playbook

My 5E playbook is now available for a limited time!

__CONFIG_colors_palette__{"active_palette":0,"config":{"colors":{"62516":{"name":"Main Accent","parent":-1}},"gradients":[]},"palettes":[{"name":"Default Palette","value":{"colors":{"62516":{"val":"var(--tcb-skin-color-0)"}},"gradients":[]}}]}__CONFIG_colors_palette__
Get Your Playbook