【问题标题】:Retrieve a set of records with SQL, then order them using Rails使用 SQL 检索一组记录,然后使用 Rails 对它们进行排序
【发布时间】:2013-12-22 07:49:51
【问题描述】:

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

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

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

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

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

【问题讨论】:

标签: mysql sql ruby-on-rails


【解决方案1】:

是的,对集合进行排序是 Ruby 的 Enumerable mixin 的一部分。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多