I really need advice on how to properly optimize mysql database queries. I'm afraid to spoil everything at the very beginning, which will turn out to be a big headache for me later.
There is a catalog with goods that have their own attributes - category, gender, age, brand, color, material, season, manufacturer. All these fields will participate in the selection/search. But not always all at once. These can be compound queries of the type:
Category, gender, presence
Category, gender, brand, color, season, availability
Category, manufacturer, availability
etc.
Exactly 2 fields will always be used - category and availability (Products that are not available in the catalog do not need to be displayed, but are not deleted from the database).
The migration is the following:
Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name', 100); $table->string('title', 100); $table->string('category_title', 50)->index()->nullable(); $table->integer('old_price')->nullable(); $table->integer('price')->nullable(); $table->integer('sale')->nullable(); $table->string('description', 500)->nullable(); $table->string('short_description', 150)->nullable(); $table->string('img_small', 115)->nullable(); $table->string('age', 15)->index()->nullable(); $table->string('gender', 10)->index()->nullable(); $table->string('brand', 50)->index()->nullable(); $table->string('color', 50)->index()->nullable(); $table->string('material', 50)->index()->nullable(); $table->string('seazon', 50)->index()->nullable(); $table->string('country', 50)->index()->nullable(); $table->integer('stock')->default('0')->index(); $table->float('rating')->nullable()->index(); $table->integer('bought')->default('0')->index(); $table->timestamps(); } At the moment, all fields participating in the index are marked with indexes. It is clear that when requesting multiple where conditions - this is not so useful. I tried using a composite index:
$table->index(['category_title', 'stock', 'gender', 'brand', 'color']); And it works for this kind of requests. But I strongly doubt if I do a Cartesian intersection on all possible query conditions and add indexes there as the best solution.
A question - how in such situation it is correct to implement index fields? I thank you in advance for your help in resolving this issue.
SHOW CREATE TABLEand the mainSELECTs. (There are a hundred different "frameworks" that make talking to the database "simpler"; I make no attempt to understand each of them.)