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

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

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:

By |2014-03-29T02:11:47+00:00March 29th, 2014|Programming & Code|0 Comments

About the Author:

Alvin Poh lives in Singapore, and is interested in marketing, techy stuff, and likes to just figure out how the two can work with each other. He can also be found on Google+.

Leave A Comment


*