11. 索引优化:单一索引
介绍
数据库表未添加索引,是另一个经常遇到的性能问题,尤其是在数据量较大的情况下。
接下来我们将以实例来讲解索引相关的性能问题,以及如何在 Laravel 中修复此问题。
请注意此系列文章只针对 MySQL 数据库,其他数据库大同小异。
测试数据
我们以 Larabbs 为测试项目。因索引在数据量小的情况下看不到效果,所以接下来我们将往 topics
里录入 100万 条假数据,同时移除此表里的索引。
首先修改迁移文件,主要是去除关联模型 ID user_id
和 category_id
的 index()
调用:
database/migrations/2019_05_07_085529_create_topics_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTopicsTable extends Migration
{
public function up()
{
Schema::create('topics', function(Blueprint $table) {
$table->increments('id');
$table->string('title')...