I am looking for a better way of doing this:
SELECT * FROM $tbl_name WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM $tbl_name ) ORDER BY id LIMIT 1;
It is slow and isn't very random, I get the same result every 10 or so query's.
This selects a random row from the table regardless of its ID.
So far I have this:
// Get amount of rows in database
$result = mysql_query("SELECT * FROM $tbl_name");
$num_rows = mysql_num_rows($result);
// Generate random number
$random_row = rand(1, $num_rows);
But I don't know how to get a certain row.
I do not mean
SELECT * FROM $tbl_name WHERE id = $random_row
Because my database has gaps in the ID column so it would sometimes fail.
Has anyone got script that can get a random result from a MySQL database without replying on IDs and is super fast? (the database contains about 20000 rows)
SELECT * FROM $tbl_name WHERE 1 ORDER BY RAND() LIMIT 1;
20,000 rows isn't really that much, the above should be fast enough.
Juhana is right by the book: "ORDER BY RAND() LIMIT 1", and of course 20k isn1t that much. Other option will be with subselects: SELECT [fields] FROM myTable, (SELECT FLOOR(MAX(myTable.id) * RAND()) AS randId FROM myTable) AS someRandId WHERE myTable.id = someRandId.randId
discussed here (please avoid select * when it`s unnecessary)
After some searching though the comments on the link Adi sent, I have found a decent solution.
SELECT * FROM $tbl_name T JOIN (SELECT CEIL(MAX(ID)*RAND()) AS ID FROM $tbl_name) AS x ON T.ID >= x.ID LIMIT 1;
Seems to be very fast and very random!