Using index in LEFT JOIN with OR condition

主宰稳场 提交于 2020-08-22 16:21:32

问题


Consider following query:

SELECT *
FROM table1
LEFT JOIN table2 ON
   table2.some_primary_key = table1.some_primary_key
LEFT JOIN table3 ON
   table3.some_primary_key = table1.some_primary_key OR -- this is the issue
   table3.column_with_index = table2.column_with_index

while I check EXPLAIN it shows me index is not in use for table3 join (however indexes are shown in "possible_keys"). Type: 'ALL'. As per manual:

Join type "ALL": A full table scan is done for each combination of rows from the previous tables.

Query is awful slow.

But when I remove one of the conditions so it will be:

LEFT JOIN table3 ON
   table3.some_primary_key = table1.some_primary_key

OR

LEFT JOIN table3 ON
   table3.column_with_index = table2.column_with_index

Mysql is using indexes properly. In EXPLAIN result indexes are shown in 'keys' column, type is 'ref'. Queries are blazing fast.

What to do to make mysql use my indexes while using OR in join statement?

I tried LEFT JOIN table3 FORCE INDEX(PRIMARY, ind_column) but no success.


回答1:


I can suggest you the use of the CASE statement,

Here is a similar question you can take and extend to your needs:

Hope this helps




回答2:


Split your query into two queries, each using a different condition from the OR, and then combine them using UNION.

SELECT *
FROM table1
LEFT JOIN table2 ON
   table2.some_primary_key = table1.some_primary_key
LEFT JOIN table3 ON
   table3.some_primary_key = table1.some_primary_key

UNION

SELECT *
FROM table1
LEFT JOIN table2 ON
   table2.some_primary_key = table1.some_primary_key
LEFT JOIN table3 ON
   table3.column_with_index = table2.column_with_index


来源:https://stackoverflow.com/questions/21134763/using-index-in-left-join-with-or-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!