The online racing simulator
ORDER BY RAND() alternatives (PHP + MySQL)
Hi,

I'm building a small app, which extracts 2 to 5 different results from a database, but I did it in a very wrong way at first.

Let's say that for these examples we need to extract 3 random results.
At first, I did it like that: ORDER BY RAND() LIMIT 3
But it started loading longer, so I decided to try and optimize it a bit.

And so I did. Right now, it gets the row count with an SQL query; php randomly picks 3 values, and I turn that in a WHERE `id` = 'x' OR `id` = 'y' OR `id` = 'z' query. I know putting LIMIT to that would make it more optimized, but I want to optimize it even more than that.

So, I was thinking of sending 3 queries to the database. Like so:
ORDER BY `id` LIMIT x,1
ORDER BY `id` LIMIT y,1
ORDER BY `id` LIMIT z,1

But, is this actually more optimized? Also, is there a better way of doing it? Or in other words: What's the best way of doing it?
Well, I will definitely look that up when I have more time, even though I am quite happy with the results I've came up with. I used a UNION. Tested it with a few queries, and like this

(SELECT `column` FROM `table` LIMIT x,1)
UNION ALL
(SELECT `column` FROM `table` LIMIT y,1)
UNION ALL
(SELECT `column` FROM `table` LIMIT z,1)

, the query takes 0.0004 sec. I won't be pulling out more than 5 results, so for me, that's more than satisfying. And as for the randomization - I left that to the PHP.

[E] It will also work very well with gaps in the ids(with UNIONs), and it will still be as random. I didn't really like where the article headed when it came down to those gaps. But maybe I just have to read it more carefully.

FGED GREDG RDFGDR GSFDG