views:

182

answers:

3

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

A: 

You can use:

SELECT id FROM table ORDER BY RAND() limit 1
Andrei Serdeliuc
No thanks, this table has much too many rows for that to be effective
Ryan Sullivan
true. but resource greedy.
dnagirl
How can it not be greedy? If we're trying to get a single row from a table with gaps, the only way to A) get a random record and B) ensure that we do return a valid record is to be exhaustive - i.e. consider the set of all primary keys in the table, and pick one at random. Using probabilistic methods, you're not guaranteed to return a valid record. If, however, that's not a concern (if you don't require that you always get a valid record back), then mwalling has the solution below.
Chris
Except for the case where your "random" number is very close to the size of the table and rows have been deleted in between the two queries causing the offset to exceed the table size, how are you not going to get a valid record?
mwalling
+2  A: 

The good solution was in What is the best way to pick a random row from a table in MySQL? question.

Ivan Nevostruev
Don't ignore the gaps in my table :P
Ryan Sullivan
A: 

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.
mwalling
OMG Ponies
True. I don't use stored procedures on a regular basis, so I don't think about using them where they would be useful :)
mwalling