简体   繁体   中英

Postgres select 3 random model instances from row?

In my Rails app I'd like to select three random instances of a model and render them on the page. Model.order('RANDOM()').limit(3) works but apparently it will put a serious hit on load times once the DB table has lots of data in it, so I'm looking for something that will hold up in more than just development.

Here's the line in my Rails view right now:

<% featured = Product.order('RANDOM()').limit(3).where.not(photo_file_name: nil, sold_value: true) %>

There's a number of ways you could do it. Which way is best depends on your setup, number of products, etc. etc.

ids = Product.pluck(:id).shuffle.slice(0,3)
featured = Product.where(id: ids)

Only two queries, but if you have a million products, that's a lot to return and shuffle in Ruby. Also small race condition in that one of the selected ids could be deleted before you make the second call.

total = Product.count
featured = 3.times.map { Product.offset(rand(total).first }

Four queries, but the last three are efficient. My syntax might be off and there may be an off-by-one error in there so double check what happens when rand(total) returns zero or total . Also, for some databases Product.count can be really inefficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM