Random Choice from Mysql DB

Discussion in 'PHP' started by SiteBuyerUK, Mar 7, 2007.

  1. #1
    Hey,

    I need a piece of code which selects a random item from a list of items in a mysql database however some items need to be more likely to be chosen than others.

    e.g. item 1 (great item 10x more likely to be chosen at random than normal)
    item 2 (good item 5x more likely to be chosen at random than normal)
    item 3 (normal item)

    I can stick item 1's, item2's and item 3's in seperate tables if needed, although would help if i didnt have to.

    I would really appreciate help on this.
     
    SiteBuyerUK, Mar 7, 2007 IP
  2. JoshuaGross

    JoshuaGross Peon

    Messages:
    411
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #2
    SELECT columns FROM table WHERE criteria ORDER BY RAND()*selection_weight DESC LIMIT 1;

    Then add a selection_weight field, and populate it with whatever values you want. Higher values = more likely being chosen.

    You can also calculate the selection_weight on the fly using existing fields, of course.
     
    JoshuaGross, Mar 7, 2007 IP
  3. SiteBuyerUK

    SiteBuyerUK Peon

    Messages:
    253
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks, so if i set item 3 which is normal to selection weight 1, and the item 1 which i wanted to be 10 x more likely to be chosen to selection_weight 10 etc it will work accordingly?
     
    SiteBuyerUK, Mar 7, 2007 IP
  4. JoshuaGross

    JoshuaGross Peon

    Messages:
    411
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Yup! It's a pretty simple system. It should work like you would expect.
     
    JoshuaGross, Mar 7, 2007 IP
    SiteBuyerUK likes this.