我只是有点被Ruby on rails Tutorial.org中的这段代码迷住了.它的add_index个部分到底是做什么的?为什么这个有3行?

    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

推荐答案

数据库索引是一种数据 struct ,可提高 表中的操作.可以使用一个或多个 列,为快速随机查找和 对访问记录进行高效排序.-TutorialPoint

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

在这个例子中

add_index :relationships, :follower_id
add_index :relationships, :followed_id

索引是为follower_idfollowed_id列创建的,这将加快查找follower_id OR followed_id的查询速度.它不会对列强制任何其他约束,比如UNIQUE.所以它们可以有相同的值

这里

add_index :relationships, [:follower_id, :followed_id], unique: true

该过程与上面相同,但约束是follower_idANDfollowed_id个组合应该是不同的.如果您try 在多行中为这些列复制相同的组合值,将会引发错误.

Database相关问答推荐

位置运算符($)工作不正确

无法向 SiriDB 添加新副本

如何以编程方式将产品添加到 Opencart 数据库

如何在 sql server 2005 中获取到数据库的详细连接列表?

为什么 COUNT() 只显示一行表格?

数据库设计:多表与单表

即使使用列入白名单的 IP,也无法连接到 Azure SQL 数据库

我应该为我创建的新创建的 PostgreSQL 模式使用什么正确的文件扩展名?

C# 连接到数据库并列出数据库

是否有任何用于 NoSQL 数据库架构迁移的工具?

如何在 Rails 中不启动事务的情况下运行迁移?

找不到类型或命名空间名称SQLConnection

有没有一种简单的方法来告诉 alembic 迁移到特定版本?

何时在关系数据库中使用枚举或小表?

将一行连接到另一个表中的多行

SQL 查询 - 如何按 null 或不为 null 进行过滤

如何在 SQL Server 中创建数据库的别名

在 SQLite 表中使用文本作为主键不好?

如何使用 group_concat 引用值

Rails 控制台 - 查找在某天创建的位置