ruby-on-rails - 具有多个值的 add_index 在 Rails 迁移中有什么作用?

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

我已通读 this并查看了this ,但我一点也不聪明:

这到底是做什么的(与传入单个列名相反),有什么优势?

add_index :resources, [:one, :two]

最佳答案

它在 resources 表的 onetwo 列上添加了一个多列索引。

声明:

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,这是四行。

关于ruby-on-rails - 具有多个值的 add_index 在 Rails 迁移中有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18342380/

相关文章:

ruby-on-rails - rails 3 : Why might my respond_to statement throw this exception when called from a POST request?

ruby-on-rails - Ruby - 在 tmp/pids/thin.pid (Thin::PidFileNotFound) 中找不到 PID

ruby-on-rails - 除了rails事件记录验证中的错误消息之外,还有没有办法返回错误代码?

ruby-on-rails - 如果 action_name Rails

ruby-on-rails - 作为非 MVC 开发人员理解 MVC 架构

mysql查询使用like无效

sql-server - 我们的数据库怎么会导致 SqlPackage 失败? (SQL72018)

ruby-on-rails - 需要一个用于 rails 的 HTTP gem

swift - 为什么我的模型不在 View Controller 中显示其成员?

ruby-on-rails - 即使删除日志文件后,Rails logger 也不会释放日志文件;它不断占用磁盘空间