带有多个值的add_index在Rails迁移中有什么作用?

时间:2013-08-20 18:25:40

标签: ruby-on-rails database ruby-on-rails-3 indexing migration

我已阅读this并查看this,但我不是更聪明的人:

这究竟是做什么的(与传入单个列名相反)又有什么优势?

add_index :resources, [:one, :two]

1 个答案:

答案 0 :(得分:9)

它在one表中的列tworesources上添加了多列索引。

声明:

add_index :resources, [:one, :two], name: 'index_resources_one_two'

相当于:

create index index_resources_one_two on resources(one, two)

传入单个列只会在该列上创建索引。例如,以下行:

add_index :resources, :one, name: 'index_resources_one'

相当于:

create index index_resources_one on resources(one)

多列索引的优点是,当您在这些多列上有条件查询时,它会有所帮助。

对于多列索引,当查询包含多个列的条件时,与单列索引相比,查询将处理较小的数据子集。

比如说我们的资源表包含以下行:

one, two 
 1,   1
 1,   1
 1,   3
 1,   4

以下查询:

select * from resources where one = 1 and two = 1;
如果定义了多列索引,

只需要处理以下两行:

one, two 
 1,   1
 1,   1

但是,如果没有多列索引,比如说只有one的索引,则查询必须处理one等于1的所有行这是四行。