Rails在哪里或选择查询链接 [英] Rails where or select for query chaining

查看:67
本文介绍了Rails在哪里或选择查询链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,查询数据库时,我知道在初始查询中使用 where 会更好,例如:

So when querying a database, I know it's much better to use where on the initial query like so:

pending = Request.where("status = ?", "Pending").order! 'created_at DESC'

但是,如果需要进一步过滤此信息,则可以使用其中选择

However, if I need to further filter this information, I can do it with either where or select:

high_p = pending.where("priority = ?", "High Priority")
normal_p = pending.where("priority = ?", "Priority")

high_p = pending.select{|x| x.priority == "High Priority"}
normal_p = pending.select{|x| x.priority == "Priority"}

我的问题是,从性能的角度来看,哪个更好?我们应该一直使用 where 吗?还是在不搜索整个数据库的情况下 select 有用例?

My question is which of these is better from a performance standpoint? Should we always use where? Or does select have a use case when the whole database isn't being searched?

推荐答案

其中从性能的角度来看要好得多。 where 修改SQL,以便数据库执行繁重的工作来标识要检索的记录。

where is much better from a performance standpoint. where modifies the SQL so that the DB does the "heavy lifting" of identifying records to retrieve.

select 检索所有满足初始 where 条件的记录,将它们转换为数组,并使用 Array#select,因此选择发生在轨道末端,并且您从数据库中检索到的记录超出了您的需要,并且进行了超出必要的处理。

select retrieves all records that meet the initial where condition, converts them into an array, and uses `Array#select' so the selection is happening at the rails end and you've retrieved more records from the db than you needed and done more processing than is necessary.

Select确实具有优势您可以根据可能无法从表列中简单提取的模型方法进行选择。例如,您可能有一个模型方法 #bad_credit?,该方法由例如信用额度,未结清发票的年龄和帐户类型确定。

Select does have an advantage in that you can select based on model methods that may not be simply extracted from table columns. For example you may have a model method #bad_credit? which is determined by, say, a credit limit, age if outstanding invoices, and type of account.

这篇关于Rails在哪里或选择查询链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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