Laravel和MySQL理解索引和复合/复合索引



在Laravel(v6.8(中,我为users表创建了以下迁移。

用户迁移

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username')->unique()->index();
$table->string('email')->unique()->index();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->enum('role', ['super', 'admin', 'manager', 'subscriber', 'user'])->default('user');
$table->boolean('is_root')->default(FALSE);
$table->rememberToken();
$table->timestamps();
$table->unique(['username', 'email'], 'user_unique_credentials');
$table->index(['username', 'email'], 'user_index_columns');
});
}

解释

我知道index的基本知识及其工作原理,但我对index在单个columncomposite/compoundindex上的理解不太清楚。

应用程序可能仅通过usernameemail进行查询,或者我可能同时对两个表进行查询。因此,正如您在我的迁移代码中看到的那样,我已经为每一列以及两列设置了index,并使用$this->index()创建了compoundindex

问题

我想知道我是否已经正确设置了所有indexes,或者按照我的方式设置是个坏主意?

如果不正确,我可以知道正确的方法吗

@danblack感谢您的帮助。

好吧,最后尝试以各种方式设置uniqueindexEXPLAIN查询,我找到了如下的最终版本。

public function up()
{
Schema::create(
'users',
function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->enum('role', ['super', 'admin', 'manager', 'subscriber', 'user'])->default('user');
$table->boolean('is_root')->default(FALSE);
$table->rememberToken();
$table->timestamps();
$table->unique(['username', 'email'], 'users_unique_credentials');
}
);
}

这样,当我们查询单个列时,它将使用自己的唯一索引。当我们使用具有多个WHERE子句的两列进行搜索时,它将使用compoundunique索引。

最新更新