开发者

Get 10 Random Records From SQLite Database

I haven't been able to find a very good way of getting 10 random records out of a sqlite database. Seen a few examples that work with mysql, but they don't seem to work well with sqlite even though I am trying t开发者_运维百科o us Random() instead of rand().

I have tried to get random numbers and then get the records by id, but for some reason I am getting nil result for a couple of them. I was curios if there was a better approach.

Also as a side note this is day 3 for my using Ruby and Rails so still a bit new to it.


How about

User.all.sort_by{rand}.slice(0,10)

?

This is just for testing, right?

Edit: No longer database-independent, but, for sqlite3:

User.find(:all, :order => "RANDOM()", :limit => 10)

and for mysql:

User.find(:all, :order => "RAND()", :limit => 10)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜