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.
But it always shows this, just the sequence changed. 1|text1|1 4|text4|2 6|text6|3 Not random choose.
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):