views:

96

answers:

2

In a Rails application, I'm using this to get a random row from a MySQL table:

contact = Contact.find(:all, :limit => 1, :order => 'RAND()')[0]

Even though the table only has about 20,000 rows it takes a couple seconds. Does anyone know of a faster way?


Update

Also tried just running the SQL in the console...

SELECT * FROM `contacts` ORDER BY RAND() LIMIT 1

It still takes a long time, like two or three seconds.

+2  A: 

I don't think my first answer will help you. Perhaps this Article will

Eric
Be sure to read the comments to that article. Potentially buggy or non-optimal behavior depending on what you're trying to do and how distributed across id-space your instances are.
Ian Terrell
A: 

Get one rand from ruby and then transform it to your primary key

dynback.com