Jump to content


Photo

Random Query


  • Please log in to reply
4 replies to this topic

#1 ssjskipp

ssjskipp
  • Members
  • PipPip
  • Member
  • 22 posts

Posted 06 July 2006 - 07:52 PM

How can I run a query that orders the data randomly?

IE:

Normally, throught PHP and MySQL, I'd do this:
<?
$order = "ORDER BY `id` ASC";
$query = mysql_query("SELECT * FROM `user` WHERE `active` = '1' $order");
$rows = mysql_num_rows($query);
if ($rows > 0){
while($data = mysql_fetch_array($query)){
echo $data["name"];
}
} else {
echo "No users";
}

But how would I do that in a random order, rather than by id and ascending?

#2 jvrothjr

jvrothjr
  • Members
  • PipPipPip
  • Advanced Member
  • 300 posts
  • LocationOhio

Posted 11 July 2006 - 02:35 PM

$query = mysql_query("SELECT * FROM `user` WHERE `active` = '1'");

This will get you the order the data was pulled from the table

If you understand everything you know nothing!

http://rcchjr.awardspace.com/

#3 ssjskipp

ssjskipp
  • Members
  • PipPip
  • Member
  • 22 posts

Posted 01 August 2006 - 05:24 AM

I got it, =D

#4 CCalo

CCalo
  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 23 August 2006 - 02:09 PM

Try something like this:

<?php
$query = "SELECT * FROM `mytable` ORDER BY RAND() LIMIT 10";
$result = mysql_query($query);
?>

This query will give you 10 randomly-sorted records from the table named "mytable".

#5 optimaximal

optimaximal
  • New Members
  • Pip
  • Newbie
  • 6 posts

Posted 30 November 2006 - 04:08 PM

This won't work in MSSQL (LIMIT is for MySQL and Oracle only & RAND isn't supported by MSSQL).

A function that will work is -

"SELECT TOP 10 * FROM `tablename` ORDER BY NEWID();"




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users