Why does Mysql use a full table scan for table A when joining another table B?

北战南征 提交于 2019-12-13 14:27:16

问题


I have a table A and a table B. I am selecting information from table A where I need only the information from table A where tabel B joins table A. I have indexes on columns that are joint and on the WHERE clause.

This is the select code:

SELECT *
FROM tableA

INNER JOIN tableB AS tableB
ON tableB.id = tableA.id
AND tableB.type = 'car'

When I use explain I can see that mysql is using a full table scan for all the rows in tableA. Further it properly uses the index to join tableB.

So what Mysql seems to be doing is scan all the rows in talbeA to see if there is a match with tableB. However as I have indexes on id of both tables I don't expect a tablescan. As my table has 50.000 rows this query is taking a few seconds (which is really too long for my application).

This is the explain:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  tableA      ALL     tableA.id       NULL    NULL    49898   
1   SIMPLE  tableB      eq_ref  tableB.type     tableB.type 4   1       Use WHere

My question: How can I optimize this query and indexes such that Mysql directly selects those rows from tableA that have a match with tableB without scanning all rows in talbeA?


回答1:


This is the maximum optimization you can get for a JOIN query refer her for more details https://cryptkcoding.com/blog/2012/04/06/how-to-optimize-mysql-join-queries-through-indexing/



来源:https://stackoverflow.com/questions/24096158/why-does-mysql-use-a-full-table-scan-for-table-a-when-joining-another-table-b

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