MySQL:选择随机条目,但权重于某些条目

问题描述:

我有一个MySQL表,表中有一堆条目,还有一列称为"Multiplier".此列的默认值(也是最常见的)是0,但可以是任何数字.

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.

我需要做的是从该表中随机选择一个条目.但是,将根据乘数"(Multiplier)列中的数字对行进行加权.值为0表示根本不加权.值1表示它的权重是表中条目的两倍,是它的两倍.值2表示它的权重是表中该条目的三倍,是它的三倍.

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.

我一直在尝试找出如何使用SELECT和RAND()进行此操作,但不知道如何进行加权.有可能吗?

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?

这个人问了同样的问题.他说的和Frank一样,但权重并不正确,有人在评论中建议使用ORDER BY -LOG(1.0 - RAND()) / Multiplier,在我的测试中,结果非常好.

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.)

缺点是您无法将权重设置为0来暂时禁用某个选项,因为最终将被零除.但是您总是可以用WHERE Multiplier > 0过滤掉它.

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.