SELECT DISTINCT *
FROM institutions
LEFT JOIN units ON Unit_Institution = Institution_Key
LEFT JOIN sites ON Site_Institution = Institution_Key OR Site_Key = Unit_Site
This request has extremely bad performance (despite indexes) because of the OR
. Removing one side of it (no matter which one) divides the query cost by thousands.
What can I provide the MySQL engine to get solve this performance issue ?
Many thanks.
3
Answers
try to join the same table two tame, the engine shouldn’t need to check the "or" each time, but he will optimize joints with indexes
I’ve tried an example by my own and it’s came out that the query with the "or" worked for 52 sec (for 10k records), instead, query with the two "join" took just 6 sec and same number of records
This
join
is not optimizable to aHASH JOIN
, this is the reason it took too long to execute.My suggestion is splitting the join condition into multiple queries, and then concatenate the results using
union
method.i.e:
You can try this :
You make two join and use coalesce to put them together.
Depending of you data it may be better.