简体   繁体   中英

Random row selection with different probabilities

I'm searching for a way to get from a table with 400-500 rows 1 random row but not with all the same probability.

For example: My table looks like:

Object - Rank

  • Object_A Top
  • Object_B Low
  • Object_C Normal

I got 3 possible ranks for an object and I would like that an object with the rank "Top" got three times more chance to get taken. It should be like there are 3 rows with Object_A in the table. Same for Normal but only two times the chance.

For now I got this code...

$result = mysqli_query($link, "SELECT * FROM objects ORDER BY RAND() LIMIT 1");

let's say your rank column has these three values:

3 top
2 normal
1 low

Then what you can do is:

$rand = rand()%3 +1;

$result = mysqli_query($link, "
   SELECT * FROM (
        SELECT * FROM objects ORDER BY RAND() 
   ) as t 
   WHERE rank >= {$rand} LIMIT 1"
);

The key is to understand the where condition: rank >= {$rand} .

  • When rand will be == 3 , 33% chances, only 1 top record will be returned.
  • When rand will be == 2 , 33% chances, only 1 top record (50% chances) or 1 normal record (50% chances) will be returned, and so on.

You can adjust the weight by assigning a different number.
For example if you want the top row returned about ~80% of the times you can assign top the value of 10 and then do:

$rand = rand()%10 +1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM