How to add “weights” to a MySQL table and select random values according to these?

后端 未结 6 694
粉色の甜心
粉色の甜心 2021-01-03 10:22

I want to create a table, with each row containing some sort of weight. Then I want to select random values with the probability equal to (weight of that row)/(weight of all

6条回答
  •  滥情空心
    2021-01-03 11:02

    The easiest (and maybe best/safest?) way to do this is to add those rows to the table as many times as you want the weight to be - say I want "Tree" to be found 2x more often then "Dog" - I insert it 2 times into the table and I insert "Dog" once and just select elements at random one by one.

    If the rows are complex/big then it would be best to create a separate table (weighted_Elements or something) in which you'll just have foreign keys to the real rows inserted as many times as the weights dictate.

提交回复
热议问题