ernest1a: First thing you want to do, is to make sure your ORDER BY field is an index.
See how long that takes, if it’s still to slow, you will need to do this in a few queries, but for this you need a sequential primary key:
SELECT MAX(id), MIN(id) FROM foo;
If you have no holes in your sequence:
my $ids = array();
for ($i =0; $i < 5; $i++) {
array_push($ids, rand($minId, $maxId));
}
SELECT * FROM foo WHERE id IN join(',',$ids)
If you have a FEW holds in there (less than 25%), and don;t care that you always get 5 results.
my $ids = array();
for ($i =0; $i < 10; $i++) {
array_push($ids, rand($minId, $maxId));
}
SELECT * FROM foo WHERE id IN join(',',$ids) LIMIT 5
If you have allot of holes in there:
SELECT * FROM foo WHERE id > rand($minId, $maxId) LIMIT 1
UNION
SELECT * FROM foo WHERE id > rand($minId, $maxId) LIMIT 1
UNION
SELECT * FROM foo WHERE id > rand($minId, $maxId) LIMIT 1
UNION
SELECT * FROM foo WHERE id > rand($minId, $maxId) LIMIT 1
UNION
SELECT * FROM foo WHERE id > rand($minId, $maxId) LIMIT 1
If you have to have a semi-random results (say you don’t care that they are 100% random), you can do:
SELECT * FROM (
SELECT * FROM foo WHERE id > max(min((rand($minId, $maxId), $maxId - 100), $minId) LIMIT 100
) ORDER BY RAND LIMIT 5;
Just test and see what works best for you.