Skip to content
Advertisement

MySQL Joining multiple tables with where clause result is too slow

Let’s say I have the following structure of tables;

and I want a result of;

So I used the following query;

I still have other tables that are connected to table1. The problem is the result is too slow even though there are only three results. I’m not that good at databases maybe I’m doing it wrong.

Advertisement

Answer

First of all, always remember that using JOIN on a large table will make your query very slow. Your database structure is already considered large since you have 16 tables that are related to the table1(That makes them 17) plus the number of data.

You only have four rows in every table at the moment, it is worth it if you mention the span time of the result of your query so we have a baseline on how slow is it and we don’t just assume.

Anyway, dividing those tables into multiple to avoid duplicate entries is a good normalization. However, you must think again about the table1. This is the core of the relation between your tables so you must know how to handle this properly.

The solution is to create an index of every table, see Gordon Linoff answer. Then use LEFT JOIN so you get every row even the corresponding table is empty or the ID didn’t match.

Then finally, pick only the column from the specific table that you really need. This is how you can enhance your query. Don’t just query it all, be smart on which data you just need.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement