Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Select Random Entry, but Weight Towards Certain Entries

I've got a MySQL table with a bunch of entries in it, and a column called "Multiplier." The default (and most common) value for this column is 0, but it could be any number.

What I need to do is select a single entry from that table at random. However, the rows are weighted according to the number in the "Multiplier" column. A value of 0 means that it's not weighted at all. A value of 1 means that it's weighted twice as much, as if the entry were in the table twice. A value of 2 means that it's weighted three times as much, as if the entry were in the table three times.

I'm trying to modify what my developers have already given me, so sorry if the setup doesn't make a whole lot of sense. I could probably change it but want to keep as much of the existing table setup as possible.

I've been trying to figure out how to do this with SELECT and RAND(), but don't know how to do the weighting. Is it possible?

like image 615
John Avatar asked Mar 10 '10 14:03

John


People also ask

How do I select a specific field in MySQL?

If you want to select only specific columns, replace the * with the names of the columns, separated by commas. The following statement selects just the name_id, firstname and lastname fields from the master_name table.

What is select * from in MySQL?

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

How do I select a third row in MySQL?

There is no such thing as the "third row" in a relational table. Rows in a table are NOT sorted. Only if you specify an order by you can talk about "the third row".


1 Answers

This guy asks the same question. He says the same as Frank, but the weightings don't come out right and in the comments someone suggests using ORDER BY -LOG(1.0 - RAND()) / Multiplier, which in my testing gave pretty much perfect results.

(If any mathematicians out there want to explain why this is correct, please enlighten me! But it works.)

The disadvantage would be that you couldn't set the weighting to 0 to temporarily disable an option, as you would end up dividing by zero. But you could always filter it out with a WHERE Multiplier > 0.

like image 177
limos Avatar answered Oct 14 '22 16:10

limos