problem with SELECT DISTINCT query

Discussion in 'PHP' started by heropage, Apr 20, 2008.

  1. #1
    I'm having the following table:

    Table paragraph
    ID | text | number
    _________________
    1|text1|1
    2|text2|1
    3|text3|1
    4|text4|2
    5|text5|2
    6|text6|3
    7|text7|3
    8|text8|3
    9|text9|3

    I need to select 3 random rows that have DISTINCT number.

    I use
    SELECT DISTINCT number, id, text, number FROM paragraph ORDER BY rand() LIMIT 3
    PHP:
    but not working.
     
    heropage, Apr 20, 2008 IP
  2. kmap

    kmap Well-Known Member

    Messages:
    2,215
    Likes Received:
    29
    Best Answers:
    2
    Trophy Points:
    135
    #2
    hi try this please

    SELECT * FROM paragraph GROUP BY number ORDER BY RAND() LIMIT 0,3

    Regards

    Alex
     
    kmap, Apr 21, 2008 IP
  3. heropage

    heropage Peon

    Messages:
    126
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    But it always shows this, just the sequence changed.
    1|text1|1
    4|text4|2
    6|text6|3

    Not random choose.
     
    heropage, Apr 21, 2008 IP
  4. heropage

    heropage Peon

    Messages:
    126
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    how to random choose number?
     
    heropage, Apr 21, 2008 IP
  5. itcn

    itcn Well-Known Member

    Messages:
    795
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    118
    #5
    Try this:

    
    <?php
      //CODE FROM WWW.GREGGDEV.COM
      function random_row($table, $column) {
          $max_sql = "SELECT max(" . $column . ") 
                      AS max_id
                      FROM " . $table;
          $max_row = mysql_fetch_array(mysql_query($max_sql));
          $random_number = mt_rand(1, $max_row['max_id']);
          $random_sql = "SELECT * FROM " . $table . "
                         WHERE " . $column . " >= " . $random_number . " 
                         ORDER BY " . $column . " ASC
                         LIMIT 1";
          $random_row = mysql_fetch_row(mysql_query($random_sql));
          if (!is_array($random_row)) {
              $random_sql = "SELECT * FROM " . $table . "
                             WHERE " . $column . " < " . $random_number . " 
                             ORDER BY " . $column . " DESC
                             LIMIT 1";
              $random_row = mysql_fetch_row(mysql_query($random_sql));
          }
          return $random_row;
      }
      
      //USAGE
      echo '<pre>';
      print_r(random_row('YOUR_TABLE', 'YOUR_COLUMN'));
      echo '</pre>';
    ?>
    
    
    Code (markup):
     
    itcn, Apr 21, 2008 IP