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

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

    I came looking for the answer to the same question - I decided to come up with this:

    id      weight
    1       5
    2       1
    
    SELECT * FROM table ORDER BY RAND()/weight
    

    it's not exact - but it is using random so i might not expect exact. I ran it 70 times to get number 2 10 times. I would have expect 1/6th but i got 1/7th. I'd say that's pretty close. I'd have to run a script to do it a few thousand times to get a really good idea if it's working.

提交回复
热议问题