Code: Select all
SELECT post FROM posts_table ORDER BY RAND()Moderator: General Moderators
Code: Select all
SELECT post FROM posts_table ORDER BY RAND()Actually it doesn't read the entire table. It creates a result set ordered based upon the primary index without scanning the entire table if the WHERE clause is missing.feyd wrote:Ordering by RAND() does actually work, however it requires reading the entire table so if it's queried often, it's probably not the best, performance-wise.
Code: Select all
$rows = $model->find();
$order = range(0, count($rows)-1);
shuffle($order);
foreach ($order as $n) {
$view->show($rows[$n]);
}Code: Select all
SELECT id FROM mytable WHERE id=FLOOR(10000 * RAND())Code: Select all
SELECT id FROM mytable WHERE id=FLOOR(10000 * 0.5)Code: Select all
// get all record ids from the table
$id_array = array();
$query = $db->Execute ("SELECT id FROM mytable" );
while (!$query->EOF)
{
$id_array[] = $query->fields['id'];
$query->MoveNext();
}
// now randomize array keys
shuffle($id_array);
// If you need a group of items just grab the first few. In this example we will use 10 Build a list of 10 record ids
$list = "";
$count = 10;
for($i = 0; $i < $count; $i++)
{
$list .= $id_array[$i];
if($i < $count - 1)
{
$list .= ", ";
}
}
// grab the 10 records
$result_array = array();
$query = $db->Execute ("SELECT * FROM mytable WHERE id IN ($list)" );
while (!$query->EOF)
{
$result_array[] = $query->fields;
$query->MoveNext();
}
// randomize the order of the returned records
shuffle($result_array);
Code: Select all
// get all record ids from the table
$id_array = array();
$query = $db->Execute ("SELECT id FROM mytable" );
while (!$query->EOF)
{
$id_array[] = $query->fields['id'];
$query->MoveNext();
}
// now randomize array keys
shuffle($id_array);
// grab the one record
$result = array();
$query = $db->Execute ("SELECT * FROM mytable WHERE id = " . $id_array[0] );
if (!$query->EOF)
{
$result_array = $query->fields;
}
Code: Select all
$random = rand();
$random segment = mysql_result($resultset,$random%mysql_numrows($resultset),"fieldname");