There are much faster methods of choosing one random row. Both of these methods below choose only one random row. You asked for two random rows. But these methods are orders of magnitude faster than doing a table-scan, so it's worth using these methods even if it takes multiple tries to get a second distinct random row.
The fastest way is to do it in two queries (I'll show in pseudocode):
$max = SELECT MAX(id) FROM bilder
$rand1 = rand(1..$max)-1
SELECT * FROM bilder WHERE id > $rand1 LIMIT 1
$id1 = id of the first row chosen
$rand2 = rand(1..$max)-1
SELECT * FROM bilder WHERE id > $rand2 AND id <> $id1 LIMIT 1
$id2 = id of the second row chosen
if $id2 = $id1, then choose a new $rand2 and query again
The problem with this is that if there are large gaps due to deleted rows, you get a higher chance of choosing the row that follows the gap.
Another fast method if you don't update the table very often is to add a column for consecutive ordering, then assign sequential values to that column in random order:
ALTER TABLE bilder ADD COLUMN rank INT UNSIGNED, ADD KEY (rank);
SET @r := 0;
UPDATE bilder SET rank = (@r:=@r+1) ORDER BY RAND();
Do this ranking once. It will be slow. Then once the rows are ranked, you can pick random value(s) fast:
$max = SELECT MAX(rank) FROM bilder;
$rand1 = rand(1..$max)
$rand2 = rand(1..$max) until $rand2 != $rand1
SELECT * FROM bilder WHERE rank IN ($rand1, $rand2);
Of course if you add or delete any rows from the table, you have to renumber the rows. Or at least you can do this more efficiently:
- If you insert, then insert the new row with a random value and update the rank of the existing row to $max+1.
- If you delete, note the rank of the deleted row and update the row with rank of $max to the rank you just deleted.