Ruby on rails 向数据模型添加索引-RubyonRails教程

Ruby on rails 向数据模型添加索引-RubyonRails教程,ruby-on-rails,ruby,database,indexing,Ruby On Rails,Ruby,Database,Indexing,我只是对RubyonRails教程中的这段代码有点着迷。添加索引的部分具体做什么?为什么有三行呢 class CreateRelationships < ActiveRecord::Migration def change create_table :relationships do |t| t.integer :follower_id t.integer :followed_id t.timestamps end

我只是对RubyonRails教程中的这段代码有点着迷。添加索引的部分具体做什么?为什么有三行呢

    class CreateRelationships < ActiveRecord::Migration
  def change
    create_table :relationships do |t|
      t.integer :follower_id
      t.integer :followed_id

      t.timestamps
    end

    add_index :relationships, :follower_id
    add_index :relationships, :followed_id
    add_index :relationships, [:follower_id, :followed_id], unique: true
  end
end
class CreateRelationships
数据库索引是一种数据结构,可以提高 表中的操作。可以使用一个或多个索引创建索引 列,为快速随机查找和 对记录访问的有效排序。-

基本上,索引用于加快查询速度

在这个例子中

add_index :relationships, :follower_id
add_index :relationships, :followed_id
follower\u id
followerd\u id
列创建索引,这将加快查询
follower\u id
followerd\u id
。它不会对列强制任何其他约束,如UNIQUE。所以它们可以有相同的值

这里


该过程与上述相同,但有一个约束条件,即
跟随者id
跟随者id
组合应该是不同的。如果您尝试在多行中复制这些列的相同组合值,则会引发错误。

谢谢您的评论,那么我是否可以将索引与书籍内容或书籍“索引”进行比较,以便更快地找到可以缩小到信息范围的区域(数据库中的表)?此外,上述索引对于查询数据库是否实用和必要?为什么,为什么不?是的,缩小信息范围会更快,但唯一的缺点是,无论何时添加/编辑行,索引都需要时间。好的,谢谢你,但是因为它们只有两列(follower\u id和followerd\u id),为什么它们需要索引?(对不起,我只是想了解一下。)。索引是否以某种方式对它们进行排序?对我来说,在一个有两列的表中添加索引似乎有点奇怪,索引对行做了什么?非常感谢您的帮助:)列数或行数无关紧要创建索引完全取决于您的选择。检查这个@barlop,我是从概念上讲的。实际上,数据库维护b树以在rid表中记录数字。当数据库删除一条记录时,它会从表的每个索引中删除该记录的条目,就像在添加记录时将条目添加到b树中一样。因此,索引会减慢影响索引的插入、删除和更新,但会加快查询速度。
add_index :relationships, [:follower_id, :followed_id], unique: true