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

后端 未结 6 695
粉色の甜心
粉色の甜心 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:11

    The problem is called Reservoir Sampling (https://en.wikipedia.org/wiki/Reservoir_sampling)

    The A-Res algorithm is easy to implement in SQL:

    SELECT *
    FROM table
    ORDER BY pow(rand(), 1 / weight) DESC
    LIMIT 10;
    

提交回复
热议问题