I am trying to force MySQL to use two indexes. I am joining a table and I want to utilize the cross between the two indexes. The specific term is Using intersect and here is a link to MySQL documentation:
http://dev.mysql.com/doc/refman/5.0/en/index-merge-optimization.html
Is there any way to force this implementation? My query was using it (and it sped stuff up), but now for whatever reason it has stopped.
Here is the JOIN I want to do this on. The two indexes I want the query to use are scs.CONSUMER_ID_1 and scs_CONSUMER_ID_2
JOIN survey_customer_similarity AS scs
ON cr.CONSUMER_ID=scs.CONSUMER_ID_2
AND cal.SENDER_CONSUMER_ID=scs.CONSUMER_ID_1
OR cr.CONSUMER_ID=scs.CONSUMER_ID_1
AND cal.SENDER_CONSUMER_ID=scs.CONSUMER_ID_2
See MySQL Docs for
FORCE INDEX
.As TheScrumMeister has pointed out below, it depends on your data, whether two indexes can actually be used at once.
Here's an example where you need to force the table to appear twice to control the query execution and intersection.
Use this to create a table with >100K records, with roughly 1K rows matching the filter
i in (2,3)
and 1K rows matchingj in (2,3)
:When doing:
you get exactly 8 matches:
Use
EXPLAIN
on the query above to get:Even if we add
FORCE INDEX
to the query on two indexesEXPLAIN
will return the exact same thing.To make it collect across two indexes, and then intersect them, use this:
Use that query with
explain
to get:This proves that the indexes are being used. But that may or may not be faster depending on many other factors.
MySQL only supports using a single index per join. If you want it to utilize two columns as indices in the join, you should create a single index over those two columns. Note that this isn't as bad as it seems, because an index over (a,b) doubles as an index over just a.
See the MySQL manual