views:

59

answers:

1

I have a model called Post, with a column called vote, and it has a big number of posts

I want to select n posts randomly that have >=x votes. n is very small compared to the number of posts

What is the best way to do this? I've tried a couple of ways that seem to be very inefficient. Thanks

+2  A: 

If you're on MySQL, you could order all the posts that meet the greater than criteria randomly and select the top n.

The actual query would look like

SELECT * FROM posts WHERE votes >= x ORDER BY rand() LIMIT n

Haven't tested this, but something like this should work in Rails:

Post.all(:conditions => ["votes >= ?", x], :order => "rand()", :limit => n)
Anurag
That doesn't work, because there's no "votes" column in the posts table.
Jaime Bellmyer
you mean it should be `vote` instead?
Anurag
I posted a new question asking about how is this operation performed internally http://stackoverflow.com/questions/2171082/in-which-order-rails-does-the-db-queries
Victor P