kylie :
Is it possible to create covering indices that span across tables? Suppose I want to optimize this query:
SELECT tbl1.col1,
tbl2.col2
FROM tbl1 INNER JOIN
tbl2 ON tbl1.col1 = tbl2.col1
WHERE tbl1.col3 = ...
Will creating these indices help?
INDEX (col3, col1) -- tbl1's
INDEX (col1, col2) -- tbl2's
Rick James :
Assuming this is the complete query...
SELECT a.col1, b.col2
FROM tbl1 AS a
INNER JOIN tbl2 AS b ON a.col1 = b.col1
WHERE a.col3 = constant
Analysis:
Because of the Where clause, tbl1 will be looked at first and this will be the optimal index:
INDEX(col3, col1) == handles the WHERE, plus it is "covering"
Then the Nested Loop Join into tbl2 will need an index starting with col
:
INDEX(col1, col2) -- again "covering"
See also http://mysql.rjweb.org/doc.php/index_cookbook_mysql
The title ("... span two tables") is deceptive. Neither of these indexes involves more than one table. INDEX(col2, col3)
is not possible because it involves more than one table.