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

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

    I'm not an expert in probability theory, but assuming you have a column called WEIGHT, how about

    select FIELD_1, ... FIELD_N, (rand() * WEIGHT) as SCORE
      from YOURTABLE
     order by SCORE
     limit 0, 10
    

    This would give you 10 records, but you can change the limit clause, of course.

提交回复
热议问题