Biased random in SQL?

后端 未结 3 1928
一向
一向 2021-01-15 19:35

I have some entries in my database, in my case Videos with a rating and popularity and other factors. Of all these factors I calculate a likelihood factor or more to say a b

3条回答
  •  青春惊慌失措
    2021-01-15 19:55

    I dare to suggest straightforward solution with two queries, using cumulative boost calculation.

    First, select sum of boosts, and generate some number between 0 and boost sum:

    select ceil(rand() * sum(boost)) from table;
    

    This value should be stored as a variable, let's call it {random_number}

    Then, select table rows, calculating cumulative sum of boosts, and find the first row, which has cumulative boost greater than {random number}:

    SET @cumulative_boost=0;
    SELECT
      id,
      @cumulative_boost:=(@cumulative_boost + boost) AS cumulative_boost,
    FROM
      table
    WHERE
      cumulative_boost >= {random_number}
    ORDER BY id
    LIMIT 1;
    

提交回复
热议问题