Ruby on rails 在Rails迁移中,使用多个值添加索引做什么?
我读了一遍又看了一遍,但我一点也不明白: 这到底有什么作用(而不是只传递一个列名)以及好处是什么?Ruby on rails 在Rails迁移中,使用多个值添加索引做什么?,ruby-on-rails,database,ruby-on-rails-3,indexing,migration,Ruby On Rails,Database,Ruby On Rails 3,Indexing,Migration,我读了一遍又看了一遍,但我一点也不明白: 这到底有什么作用(而不是只传递一个列名)以及好处是什么? add_index :resources, [:one, :two] 它在resources表中的one和two列上添加多列索引 声明: add_index :resources, [:one, :two], name: 'index_resources_one_two' 相当于: create index index_resources_one_two on resources(one, t
add_index :resources, [:one, :two]
它在
resources
表中的one
和two
列上添加多列索引
声明:
add_index :resources, [:one, :two], name: 'index_resources_one_two'
相当于:
create index index_resources_one_two on resources(one, two)
create index index_resources_one on resources(one)
传入单个列只会在该列上创建索引。例如,以下行:
add_index :resources, :one, name: 'index_resources_one'
相当于:
create index index_resources_one_two on resources(one, two)
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
的所有行,这是四行