Is it a good idea to replace the original query?
Yes, but there's a simpler way of expressing this:
SELECT * FROM definiciones WHERE id >= ? ORDER BY id LIMIT 1
With ?
set to a random number between 0 and the maximum ID in the table.
Now, an improvement: If there are any gaps in the values of id
, the results from the previous method will be skewed somewhat. (For instance, if there are no rows with id < 100
, then a row with id = 100
will be selected much more often than one with id = 101
.) You can avoid this by using a separate column for randomization. First, you will need to add the column:
ALTER TABLE definiciones ADD COLUMN randomval FLOAT NOT NULL,
ADD KEY randomval (randomval);
UPDATE TABLE definiciones SET randomval = RAND();
Then, to select a fairly chosen random item:
SELECT * FROM definiciones WHERE randomval > ? LIMIT 1;
using a random value between 0 and 1 for the parameter.
There is a small chance that this will return no rows (if RAND()
selects a value greater than the highest value in the table). If this happens, repeat the query.
You will need to set randomval = RAND()
when inserting new rows into the table.