当数据库中的数据量达到一定的水平之后,由于之前的一些不合理的设计,特别是索引的设计,都会产生慢查询,这不,最近一直在处理慢查询的事情,最近遇到一个慢查询是因为mysql server升级之后出现的,没有用到最优的索引,这种情况下我们怎么使用真正最优的索引呢?google一下,有个语法叫force index。
那么,Rails里怎么用force index,官方文档里没有答案,google一下,在Stack Overflow找到了答案:
class Issue
def self.use_index(index)
# update: OP fixed my mistake
from("#{self.table_name} USE INDEX(#{index})")
end
end
# then
Issue.use_index("bla").where(some_condition: true)
在这个答案上我优化了一下:
def force_use_index(index)
if index.blank?
from("#{self.table_name}")
else
from("#{self.table_name} USE INDEX(#{index})")
end
end