How to select one row randomly taking into account a weight?

后端 未结 7 1943
一生所求
一生所求 2020-11-29 11:58

I have a table which looks like that:

id: primary key
content: varchar
weight: int

What I want to do is randomly select one row from this t

相关标签:
7条回答
  • 2020-11-29 12:58

    I think the simplest is actually to use the weighted reservoir sampling:

    SELECT
      id,
      -LOG(RAND()) / weight AS priority
    FROM
      your_table
    ORDER BY priority
    LIMIT 1;
    

    It's a great method that lets you choose M out of N elements where the probability to be chosen for each element is proportional to its weight. It works just as well when you happen to only want one element. The method is described in this article. Note that they choose the biggest values of POW(RAND(), 1/weight), which is equivalent to choosing the smallest values of -LOG(RAND()) / weight.

    0 讨论(0)
提交回复
热议问题