[英]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. 在我的Rails应用程序中,我想选择一个模型的三个随机实例,并将其呈现在页面上。
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. Model.order('RANDOM()').limit(3)
可以工作,但是显然一旦数据库表中有很多数据,它将严重影响加载时间,因此我正在寻找可以在不只是发展。
Here's the line in my Rails view right now: 现在是我的Rails视图中的行:
<% 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. 只有两个查询,但是如果您有一百万种产品,那么在Ruby中返回和洗牌将有很多。 Also small race condition in that one of the selected ids could be deleted before you make the second call.
同样,在进行第二次通话之前,可以删除所选ID之一的小比赛条件。
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
. 我的语法可能关闭,并且那里可能有一个错误的错误,因此请仔细检查
rand(total)
返回零或total
时会发生什么。 Also, for some databases Product.count
can be really inefficient. 同样,对于某些数据库,
Product.count
可能确实效率低下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.