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

Und*_*ion 2 database migration indexing ruby-on-rails ruby-on-rails-3

我已经阅读了这篇文章并对此进行了研究,但我并不聪明:

这究竟是做什么的(而不是传入一个列名),有什么好处?

add_index :resources, [:one, :two]
Run Code Online (Sandbox Code Playgroud)

vee*_*vee 9

它增加了对列的多列索引one,并tworesources表中.

该声明:

add_index :resources, [:one, :two], name: 'index_resources_one_two'
Run Code Online (Sandbox Code Playgroud)

相当于:

create index index_resources_one_two on resources(one, two)
Run Code Online (Sandbox Code Playgroud)

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

add_index :resources, :one, name: 'index_resources_one'
Run Code Online (Sandbox Code Playgroud)

相当于:

create index index_resources_one on resources(one)
Run Code Online (Sandbox Code Playgroud)

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

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

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

one, two 
 1,   1
 1,   1
 1,   3
 1,   4
Run Code Online (Sandbox Code Playgroud)

以下查询:

select * from resources where one = 1 and two = 1;
Run Code Online (Sandbox Code Playgroud)

如果定义了多列索引,则只需要处理以下两行:

one, two 
 1,   1
 1,   1
Run Code Online (Sandbox Code Playgroud)

但是,如果没有多列索引,例如说只有一个索引,one那么查询必须处理所有one等于1四行的行.