开发者

Select n objects randomly with condition in Rails

开发者 https://www.devze.com 2022-12-19 04:01 出处:网络
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

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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号