Displaying random but fair MySQL results

Discussion in 'Programming' started by jsamdirect, May 1, 2008.

  1. #1
    I am trying to display random MySQL results for featured items on my site. While I want it to be random, I also want it to be "fair".

    The scenario is like this; I have 4 featured customers. Customer 1 has 100 items, Customer 2 has 75 items, Customer 3 has 50 items, and Customer 4 has 25 items. I am displaying 4 items at a time. Note that I use 4 Customers as an example but could have 1000's.

    Currently, items from Customer 1 show more then the others because there are more records in the db for this customer. How can I make it so the items are displayed more "fairly" yet random? Ideally, it would only display one item per customer.

    Here is the MySQL query I am currently using, it is very simply.

    SELECT fields WHERE some='condition' ORDER BY RAND() LIMIT 4
     
    jsamdirect, May 1, 2008 IP
  2. apmsolutions

    apmsolutions Peon

    Messages:
    66
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    What about something like this:


    select t1.*
    from tableName t1
    join (select columnName, min(ID) as MinID
    from tableName group by columnName) t2 on t1.columnName= t2.columnName
    WHERE t1.ID= t2.MinID
    ORDER BY RAND() LIMIT 4
     
    apmsolutions, May 1, 2008 IP
  3. jsamdirect

    jsamdirect Peon

    Messages:
    61
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I'll have to test it and let you know ... looks like it may just do what I need. Thanks for the help!
     
    jsamdirect, May 1, 2008 IP
  4. jsamdirect

    jsamdirect Peon

    Messages:
    61
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Seems to be better results then RAND() but slower...
     
    jsamdirect, May 1, 2008 IP