mysql - Laravel 5.7 + MySQL : Multiple "where" conditions in a query. 每个 "where"列的索引还是组合所有列的单个复合索引?

标签 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

没有比这更简单的查询了,对吧?现在,每次获取记录时,我都会使用其独特的 slug 和两个 bool 标志(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)。我还在某些列上定义了唯一索引以保证复合唯一性,但这也是无关紧要的。

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

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

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

或者:

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

enter image description here

我认为这两个例子不一样?有人可以解释哪种方法更好并且适合这种特殊情况吗?

最佳答案

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

一些数据库引擎允许在索引中包含一列,这可以帮助您进行额外的读取,但我不相信 MySQL 支持这一点。

如果您正在查询 slug,那么您肯定希望为其建立索引。

关于mysql - Laravel 5.7 + MySQL : Multiple "where" conditions in a query. 每个 "where"列的索引还是组合所有列的单个复合索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54175160/

相关文章:

mysql - Ruby on Rails 安装、Windows10 上的 Ubuntu #<Mysql2::Error: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)>

mysql - 如何在 DBIC 中找到未知数量结果集的并集?

php - Mockery 和 Laravel 构造函数注入(inject)

mysql - 具有多态连接的 Laravel 查询生成器不适用于 SQLite

php - 从flash上​​传位图数据到laravel路由

php - Laravel:表单验证字符串长度错误消息导致异常

php - laravel 4 中的每周电子邮件通讯

mysql - MySQL 中的条件语句

mysql - 如果我想在未来使用巨大的 id 值,我需要选择什么类型的 id [MySql]

mysql - 使用不同的日期字段排序