How to optimize MySQL query which contains table and left join of sql view
-
14-11-2019 - |
Question
I have this query:
SELECT a.id, b.discount FROM (a LEFT JOIN b ON b.id_a = a.id);
EXPLAIN command for this query is this:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE a index NULL PRIMARY 4 NULL 1489 Using index
1 SIMPLE b ALL NULL NULL NULL NULL 819
A is table with 1489 rows and B is a SQL view. Now I understand, that MySQL has to do 1489*819 operations which is way too not-optimized operation. If B was a table, I would create an index for column id_a, but I have no idea what to do with SQL view.
Anybody can help ?
Solution
I would look at the view, and try to go to the raw tables that qualify the element you are concerned with finding exists or not. And ensure the root table of "b" view has an index on that key.
OTHER TIPS
Instead of working with a view (which is unindexed), you could also try creating a temporary table with indexes. We did that for some lengthy reporting queries and got some impressive speed improvements as a result (YMMV of course).
Switching the table and view might help.
example:
SELECT a.id, b.discount FROM (b RIGHT JOIN a ON b.id_a = a.id);