使用 SQL 检索一组记录,然后使用 Rails 对它们进行排序 [英] Retrieve a set of records with SQL, then order them using Rails

查看:31
本文介绍了使用 SQL 检索一组记录,然后使用 Rails 对它们进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Rails 3.2 和 MariaDB.我的表有 500,000 行.在通常的查询中,我们会在其中添加 order 子句,如下所示:

Using Rails 3.2 and MariaDB. My table has 500,000 rows. In usual query, we will add the order clause in it, like this:

# takes 4000ms to load, returns 100 records
@shops = Shop.where(:shop_type => 'fashion').order('overall_rating DESC')

如果去掉order,加载时间大大减少:

If we remove the order, the load time is greatly reduced:

# takes 20ms to load, returns 100 records
@shops = Shop.where(:shop_type => 'fashion')

是否可以先检索@shops 100 条记录,然后使用Rails 按overall_rating DESC 对它们进行排序,而不涉及SQL?或者,将查询分成 2 部分:首先检索 100 条记录,然后对该组记录进行排序.这可以大大提高性能.

Is it possible to first retrieve the @shops 100 records, then use Rails to order them by overall_rating DESC without involving SQL? Or, separate the queries to 2 parts: first retrieve 100 records, then order that set of records. This can greatly improve the performance.

推荐答案

是的,对集合进行排序是 Ruby 可枚举 mixin.

Yes, sorting a collection is part of Ruby's Enumerable mixin.

@shops = Shop.where(:shop_type => 'fashion')
@shops.sort! { |a,b| b.overall_rating <=> a.overall_rating }

这篇关于使用 SQL 检索一组记录,然后使用 Rails 对它们进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆