Laravel 5.7 + MySQL:查询中有多个“ where”条件。每个“ where”列的索引还是组合所有列的单个组合索引?

时间:2019-01-14 02:34:55

标签: mysql laravel

我想提高查询性能,该查询负责从表中获取库存产品。非常简单的查询:

select 
    * -- (I know I should not use "*")
from 
    sync_stock_products 
where 
    slug = 'cable-usb-31-type-c-to-a-male-to-male' and 
    dead = 0 and 
    sync_active = 1 
limit 
    1

再没有比这更简单的查询了吧?现在,每次获取记录时,我都会使用其唯一的子段和两个布尔标志(3个where条件)。该产品不能失效,必须处于活动状态。我认为上述条件的含义无关紧要。

enter image description here

当前,迁移看起来像:

public function up()
{
    Schema::create('sync_stock_products', function (Blueprint $table) {
        $table->uuid(SyncInterface::SYNC_MODEL_PRIMARY_KEY_COLUMN_NAME);
        $table->string('stockcode');
        $table->string('slug');
        $table->boolean('dead');
        $table->boolean('stkind1');
        (...) heaps of other columns, removed for shorter snippet
        $table->text('field1')->nullable();
        $table->text('smalpic')->nullable();
        $table->text('highrespic')->nullable();
        $table->text('picture4')->nullable();
        $table->text('picture5')->nullable();
        $table->boolean('nonreturn');
        $table->boolean('sync_flag');
        $table->boolean('sync_active');
        $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

        // Indexes
        $table->primary(SyncInterface::SYNC_MODEL_PRIMARY_KEY_COLUMN_NAME);
        $table->unique(SyncInterface::COMPOSITE_KEYS['sync_stock_products']);  
    });
}

我已经在uuid上有了主索引(但是在上面的查询中我没有使用uuid)。我还在某些列上定义了unique索引以保证复合唯一性,但这也不相关。

我的问题是我想用索引覆盖所有三列。

我应该将每一列放在单独的索引中,例如:

$table->index('slug');
$table->index('dead');
$table->index('sync_active');

或者:

$table->index(['slug', 'dead', 'sync_active']);

enter image description here

我假设两个示例都不相同?有人可以解释哪种方法更好,并适合这种情况吗?

1 个答案:

答案 0 :(得分:0)

无需索引is_active或dead。这些列的基数非常低,对数据库没有帮助。

某些DB引擎允许在索引中包含一列,这可以使您获得更多的阅读机会,但是我不认为MySQL支持。

如果您要查询段塞,您肯定要为其编索引。