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

Similar Posts:

Leave a reply:

Your email address will not be published.


Site Footer

Sliding Sidebar


The contents on this blog are not intended as professional advice. The author disclaims any liability, loss, or risk taken by individuals who directly or indirectly act on the information contained on this blog.