Question

I'm looking to get a random row from MySQL without using too much time or resources on the system. I don't care about weather the code given is PHP or MySQL based, however please note there are 'gaps' in my table.

My table columns are 'id' (Primary key, auto increment), varchar, int, int

I'd like it to be as random as possible

Was it helpful?

Solution

I would do it in two queries, and three steps overall.

  1. Find the number of rows in the table using SELECT COUNT(*) FROM your_table
  2. Use PHP's math functions to find a random number between 0 and the number of rows
  3. Get the actual data you want using SELECT * FROM your_table LIMIT 200, 1, where 200 is the random number you calculated in step 2.

OTHER TIPS

You can use:

SELECT id FROM table ORDER BY RAND() limit 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top