【问题标题】:SQL query performance for a 'map' statement'map' 语句的 SQL 查询性能
【发布时间】:2011-03-08 09:47:52
【问题描述】:
我正在使用 Ruby on Rails 3,我想知道这些查询语句的性能差异是什么:
# Case 1
accounts = ids.map { |id| Account.find_by_id(id) }
# Case 2
accounts = ids.map { |id| Account.where(:id => id).first }
还有其他方法可以做得更好? 如果 ids 是 100,我如何才能限制搜索直到帐户达到 5 个?
【问题讨论】:
标签:
sql
ruby-on-rails
ruby
performance
ruby-on-rails-3
【解决方案1】:
正如@RubyFanatic 所说,这两者之间没有真正的区别(它们都会生成相同的查询),但是有一种更好的方法:
accounts = Account.where(:id => ids)
这将生成像select * from accounts where accounts.id in (1,2,3) 这样的sql,并且比一次找到它们要快得多。
如果您只想使用 id 数组中的 5 个,则需要决定使用哪 5 个。例如,如果你想使用前 5 个;
accounts = Account.where(:id => ids[0..4])
或者,您可以使用limit,但是如果ids数组很大,这使得查询仍然需要做更多的工作:
accounts = Account.where(:id => ids).limit(5)
【解决方案2】:
这两个查询应该没有性能差异。他们实际上是在做同样的事情。第二个语句可能会稍微慢一些,但它是如此微不足道,甚至没有关系。