我们的 Rails 3 应用程序中有一个 SQL 查询。
@followers
返回后面的用户 ID 数组current_user
。
@followers = current_user.following
@feed_items = Micropost.where("belongs_to_id IN (?)", @followers)
有没有更有效的方法来做这个查询?
我们的 Rails 3 应用程序中有一个 SQL 查询。
@followers
返回后面的用户 ID 数组current_user
。
@followers = current_user.following
@feed_items = Micropost.where("belongs_to_id IN (?)", @followers)
有没有更有效的方法来做这个查询?
您拥有的查询无法真正优化。可以通过添加索引来加快速度belongs_to_id
(无论如何,您几乎总是应该为外键做这件事),但这不会改变实际的查询。
不过,有一种更简洁的方式来编写IN
查询:
Micropost.where(:belongs_to_id => @followers)
其中@followers
是 的值数组belongs_to_id
。
对我来说看起来不错。
但是,如果您正在寻找代码中真正的最小字符数,您可以更改:
Micropost.where("belongs_to_id IN (?)", @followers)
至
Micropost.where("belongs_to_id = ?", @followers)
读起来容易一些。
Rails 将看到数组并执行IN
.
与往常一样,ruby 语言的主要目标是可读性,因此很少有改进帮助。
至于查询效率低下,您应该检查该字段的索引。
对于每个数据库,它们往往更具体一些——您只指定了通用 sql。在你的问题中。