我想提高负责从表中获取库存产品的查询的性能。极其简单的查询:
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
条件)。产品不能死,必须处于事件状态。我认为这与上述条件的含义无关。
目前,迁移如下:
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']);
我认为这两个例子不一样?有人可以解释哪种方法更好并且适合这种特殊情况吗?
最佳答案
无需索引 is_active 或 dead。这些列的基数非常低,对数据库没有帮助。
一些数据库引擎允许在索引中包含一列,这可以帮助您进行额外的读取,但我不相信 MySQL 支持这一点。
如果您正在查询 slug,那么您肯定希望为其建立索引。
关于mysql - Laravel 5.7 + MySQL : Multiple "where" conditions in a query. 每个 "where"列的索引还是组合所有列的单个复合索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54175160/