[Solved] Performance, sql heavy join vs multiple small request

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `category1_to_category2` ADD INDEX `category1_category_idx_id_category1` (`id_category1`);
ALTER TABLE `category2` ADD INDEX `category2_idx_id` (`id`);
ALTER TABLE `category2_to_item` ADD INDEX `category2_item_idx_id_category2` (`id_category2`);
ALTER TABLE `item` ADD INDEX `item_idx_id` (`id`);
The optimized query:
SELECT
        c1.name AS c1name,
        c2.name AS c2name,
        i.name 
    FROM
        category1 c1 
    LEFT JOIN
        category1_to_category2 c1tc2 
            ON c1.id = c1tc2.id_category1 
    LEFT JOIN
        category2 c2 
            ON c1tc2.id_category2 = c2.id 
    LEFT JOIN
        category2_to_item c2ti 
            ON c2.id = c2ti.id_category2 
    LEFT JOIN
        item i 
            ON c2ti.id_item = i.id

Related Articles



* original question posted on StackOverflow here.