How to extract 3 mysql rows - 2 random and one not

Discussion in 'MySQL' started by olegb, Dec 24, 2008.

  1. #1
    hello everybody!
    I need a little suggestion or help on how could I extract 3 rows from mysql at the same time, 2 being randomly selected and one not.
    the problem I'm struggling:
    I intend to make a quizz, I have a database (rows: id, question, correct_answer)
    I want to generate 3 answers automatically, from them 1 will be true and 2 fake -- randomly selected from other questions' correct_answers.
    hope made myself understandable, maybe someone's facing this problem too.
    thanks for your time
     
    olegb, Dec 24, 2008 IP
  2. chisara

    chisara Peon

    Messages:
    141
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #2
    (SELECT correct_answer FROM mytable WHERE question=X) UNION (SELECT correct_answer FROM mytable WHERE question IS NOT X ORDER BY RAND() LIMIT 2) ORDER BY BY RAND();

    Should by roughly what you are looking for.
    First part of the union gets the correct answer, the second part gets two other answers and then the three are ordered random.
     
    chisara, Dec 25, 2008 IP
    shenron and olegb like this.
  3. olegb

    olegb Peon

    Messages:
    86
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    thanks chisara,
    I eddited and modified it a bit, because my database is a little bit more than I showed here, but it works!
    great tip!
     
    olegb, Dec 26, 2008 IP
  4. chisara

    chisara Peon

    Messages:
    141
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Glad to be of assistance and a happy new year :)
     
    chisara, Jan 5, 2009 IP
  5. 123GoToAndPlay

    123GoToAndPlay Peon

    Messages:
    669
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #5
    sorry to dig this up but i want to use the same
    
    $sql= " (SELECT * FROM table WHERE id = 131) UNION ( SELECT * FROM table ORDER BY RAND())";
    
    $query_limit_rsImages = sprintf("%s LIMIT %d, %d", $sql, $startRow_rsImages, $maxRows_rsImages);
    
    PHP:
    Would the LIMIT be the cause of strange behavior?
     
    123GoToAndPlay, Apr 21, 2009 IP
  6. chisara

    chisara Peon

    Messages:
    141
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Since my php/sprintf knowledge is non existent.
    Could you post the SQL statements that are send into the database server ?
    P.S. What is your strange behaviour?
     
    chisara, Apr 21, 2009 IP