我的协会就像这样
我正在查询field_values表,以获得field_id按field_id分组的字段:
def field_values
FieldValue.where(field_id: @field_ids)
.pluck(:id, :value, :field_id, :active, :old_value)
.map { |obj| { id: obj[0], value: obj[1], field_id: obj[2],
active: obj[3], old_value: obj[4] } }
.group_by { |a| a[:field_id] }
end
上面的方法执行这个SQL需要20ms才能获取30k记录
SELECT id, value, field_id, active, old_value FROM field_values WHERE field_id IN (85, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 117, 118, 119);
然后构建我的@shared_fields obj以在其中插入field_values:
@shared_fields
{
id: 1
field:
{
id: 11,
field_values:
[
{
id: 111,
value: 'abc',
field_id: 11,
active: true,
old_value: nil
}
{
id: 112,
value: 'pqr',
field_id: 11,
active: true,
old_value: nil
}
]
}
}
def construct_obj
field_values.each do |id, values|
sh_field = @shared_fields.detect { |shf| shf[:field][:id] == id }
next unless sh_field
sh_field[:field][:field_values] = values
end
end
关于我们如何优化sql查询以及循环遍历170 ms的分组对象的任何想法。