Tech-Tidbit: MySQL Weighting

I’m still rather disappointed with my options for weighting random results in MySQL, but I’ve done the best I can do with it. It’s more about figuring out what numbers you use for the weighting rather than the calculation itself. The query itself ends with:

[mysql]
ORDER BY RAND() * weight_fieldname
[/mysql]

Now, my possible weights from weight_fieldname are 5, 20, 100. 5 is the default weight for every record – 20 increases the chances of the record a bit and 100 pretty much sets the record as an exclusive result. Now, if you only have a single weight applied then setting it to 0 will reduce the weight of an item, however this is very difficult when you start having multiple weights.

One additional problem is that if you have a serious amount of records, using ORDER BY RAND() is going to be a performance hit.

Leave a Reply