top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Optimize Joins in MySQL?

0 votes
336 views
How to Optimize Joins in MySQL?
posted Jul 2, 2014 by Rahul Mahajan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Improving the WHERE clause

EXPLANATION shows that MySQL is only utilizing one index (type_id) for selecting the rows that match the WHERE clause, even though you have multiple criteria in the clause.

To be able to utilize an index for all of the criteria in the WHERE clause, and to reduce the size of the result set as quickly as possible, add a multi-column index on the following columns on the vehicles table:

(status, date_from, date_to, type_id, price)

The columns should be in order of highest cardinality to least.

For example, vehicles.date_from is likely to have more distinct values than status, so put the date_from column before status, like this:

(date_from, date_to, price, type_id, status)

This should reduce the rows returned in the first part of the query execution, and should be demonstrated with a lower row count on the first line of the EXPLAIN result.

We will also notice that MySQL will use the multi-column index for the WHERE in the EXPLAIN result. If, by chance, it doesn't, you should hint or force the multi-column index.

Removing the unnecessary JOINs

It doesn't appear that we are using any fields in any of the joined tables, so remove the joins. This will remove all of the additional work of the query, and get it down to one, simple execution plan (one line in the EXPLAIN result).

Each JOINed table causes an additional lookup per row of the result set. So, if the WHERE clause selects 5,000 rows from vehicles, since we have 8 joins to vehicles, we will have 5,000 * 8 = 40,000 lookups. That's a lot to ask from our database server.

answer Jul 3, 2014 by Vrije Mani Upadhyay
...