tags:

views:

36

answers:

3

Is there any built-in function except order by random() to select a random record in mysql table?

A: 

I don't think so... why don't you want to use the one that works?

BTW, I'm pretty sure it is ORDER BY RAND().

I've read it can be a performance problem on many rows... do you have many rows?

alex
no,i have about 1000 tips but i have around 10000 users, it will slow down the process and also the tips are based on category.
RSGanesh
+1  A: 

No, but you can make it into two questions. In pseudo-PHP-and-MySQL-code:

$max = SELECT COUNT(*) FROM example;
$rand = rand(0, $max-1);
SELECT * FROM example LIMIT $rand, 1;

The right way would probably be to make it into a stored procedure.

Emil Vikström
Thanks for your immediate response. Actually i dont want to run two select queries as i am using this for displaying tips for user randomly. Is there any other idea?
RSGanesh
@rshivaganesh - this method has *much* better performance than `order by rand()`
nickf
Not that I'm aware of. I would go with ORDER BY RAND() on a small table. Maybe you can cache the result from the first query in some way?
Emil Vikström
@Emil sure. `$rand = rand(0, $max-$num); LIMIT $rand, $num;` ;)
Col. Shrapnel
A: 
SELECT * FROM users ORDER BY RAND() Limit 0, 1;
Salil
that should be `LIMIT 0, 1` or `LIMIT 1`
nickf
@nickf does it *really* matter? ;-)
Col. Shrapnel
@nickf :- I edit it but i think 'Limit 1, 1;' also not wrong as he want random data to display.
Salil
what if there's only one row..?
nickf
that's why i edit it but yes then order by rand() will always result same row :)
Salil
Yes, order by rand() will always result one from some set of records
RSGanesh